Home Tutorial Java Io Java Parse text file with several delimiters

 
 

Java Parse text file with several delimiters
Posted on: November 23, 2009 at 12:00 AM
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

Related Tags for Java Parse text file with several delimiters:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.