Parsing Text Files in Java

July 14, 2008

The following code is designed to parse (comma, tab, etc.) delimited files in Java.

private static ArrayList parseDelimitedFile(String filePath, String delimiter) throws Exception
{
  ArrayList rows = new ArrayList();

  FileReader fr = new FileReader(filePath);
  BufferedReader br = new BufferedReader(fr);

  String currentRecord;
  while((currentRecord = br.readLine()) != null)
    rows.add(currentRecord.split(delimiter));

  br.close();

  return rows;
}

Entry Filed under: CodeSnippet, Java. .

2 Comments Add your own

  • 1. jk  |  July 28, 2008 at 3:54 am

    Will this help to parse a huge text file ( about 500 Mb ).

    Please help me on this. Actually I need to parse from a big file to a table. Also I need to do some data manipulation while parsing the text files lines fileds with exisiting table.

    What would be the fastest way to do this.

    Thanks

  • 2. utah_guy  |  July 28, 2008 at 2:34 pm

    This should work to parse large files. I have used similar code to process multi-GB files. What you’d have to change, though, is that this code stores the results in an ArrayList object, so if you are processing huge files it will consume a lot of memory. But if you are pulling the data from a file and then storing it in a database immedidately, you should not have to worry about memory. If you’re wanting some code samples on how to manipulate the text after pulling from the file and before inserting into the database, please send me more details, and I’ll see what I can cook up.

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Categories

Archives

Top Posts