How to Read Delimited File in Java

If you have to read delimited file in Java and parse it then you can do it using the following two ways-

1- Using Scanner class with useDelimiter() method.
2- Read file using BufferedReader line by line and then split each line using split() method.

Using Scanner class to read delimited file in Java

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches white space. The scanner can also use delimiters other than white space for that useDelimiter() method is used. Let’s see some examples of using Scanner class to read delimited file in Java.

Reading CSV file using Scanner in Java

Here is an example CSV file which denotes Account From, Account To and Amount Transferred.

1001,1003,2000
1006,2004,3000
1005,1007,10000

Which you want to read using Scanner class and parse it to display the fields.

Output

Reading pipe(|) delimited file using Scanner in Java

Here is another example Java program showing how you can read pipe delimited data using Scanner in Java.

1001|1003|2000
1006|2004|3000
1005|1007|10000

Output

Since pipe symbol is a reserved character you do need to escape it, that is why lineScanner.useDelimiter(“\\|”); is used.

Using split() method to split delimited data

Another way to read delimited file in Java is to read file line by line, you can use BufferedReader to read the file and then split delimited data using split method. If we take the same pipe delimited file as used above then the Java example is as follows.

Output

That’s all for the topic How to Read Delimited File in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.