Thursday, April 18, 2013

Parsing delimited text using java Scanner


We all have come across the task of processing delimited text numerous times.

Since 1.5 version java provides the java.util.Scanner class which contains useful methods to process delimited text.
Consider a comma delimited text containing employee details firstname, lastname, department, city, state, zip.

For example lets parse the comma separated text
john, doe, d1, true, city1, state1, 1234

We can process this text using java Scanner as


























Here is our Employee class,















Note that useDelimiter takes a regular expression as an argument.
The regular expression "\\s*,\\s*" will consider any comma with preceeding or succeeding whitespaces as a delimiter.

Lets run this with the below main method:









The following output is printed:

Employee name is john doe

No comments:

Post a Comment