Share on Google+Share on Google+

Java Parse text file with several delimiters

Advertisement
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

Advertisements

Advertisement

Posted on: November 23, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.