Java Parse text file with several delimiters


 

Java Parse text file with several delimiters

In this section, you will learn how  to parse file with several delimiters and line feeders in Java.

In this section, you will learn how  to parse file with several delimiters and line feeders in Java.

Parse text file with several delimiters

In this section, you will learn how  to parse file with several delimiters and line feeders. We have used BufferedReader class in order to read the file. All the delimiters and the line feeders have been replaced using regular expression with replaceAll() method and replace() method and we get  the values present between the tags, spaces etc.

Here is the file.txt:

<cr><lf><lf>
^^^<rsphdr><cr><lf>
M^^<ctag>^COMPLD<cr><lf>
(^^^"<aid>[,<aidtype>]:<ntfcncde>,<condtype>,<srveff>, [<ocrdat>],
[<ocrtm>], [<locn>], [<dirn>] [, <tmper>]
[:[<conddescr>], [<aiddet>] [,<obsdbhvr>
[,<exptdbhvr>]]
[:[<dgntype>][,<tblislt>]]]"<cr><lf>)* ;

Here is the code:

import java.io.*;
import java.util.regex.*;

public class Read {
	public static void main(String[] args) throws Exception {

		BufferedReader bf = new BufferedReader(new FileReader("C:\\file.txt"));
		String line;
		String data = "";
		while ((line = bf.readLine()) != null) {
			String replacedData = line.replaceAll("[|,|:|/|\\|\'><*}{^();]",
					" ").replaceAll("\"", "").replace('[', ' ').replace(']',
					' ');
			System.out.println(replacedData);
		}
	}
}

Output:

cr  lf  lf
rsphdr  cr  lf
M   ctag  COMPLD cr  lf
aid    aidtype    ntfcncde   condtype   srveff     ocrdat
ocrtm      locn      dirn       tmper
conddescr      aiddet      obsdbhvr
exptdbhvr
dgntype     tblislt     cr  lf

Ads