Read values from CSV file using BufferedReader and split using StringTokenizer

In my previous post I have explained about the StringTokenizer object. Please click here to review my previous post on StringTokenizer.

In this example we are going to read the input value from the CSV file and split them by a pipe ("|") delimiter and iterate them by using StringTokenizer object.

First of all lets create a csv file and input some test data to it.

test.csv



Now lets create the java class in which we are going to read the csv file by using BufferedReader objec. Then, we are going to use the StringTokenizer object and will specify the delimiter as pipe ("|"). The next step is to iterate the each element that we are getting and displaying them. Please have a look at the below code snippet.

ReadFromFile.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class ReadFromFile {

    public static void main(String[] args) {

        BufferedReader br = null;
        try {
            String line;
            br = new BufferedReader(new FileReader(
                    "c:/Users/Amzi/Desktop/test.csv"));

            while ((line = br.readLine()) != null) {
                System.out.println(line);
                System.out.println("-------------");

                StringTokenizer stringTokenizer = new StringTokenizer(line, "|");
               
                while (stringTokenizer.hasMoreElements()) {

                    Integer id = Integer.parseInt(stringTokenizer.nextElement()
                            .toString());
                    Double balance = Double.parseDouble(stringTokenizer
                            .nextElement().toString());
                    String username = stringTokenizer.nextElement().toString();

                    StringBuilder sb = new StringBuilder();
                    sb.append("\nId : " + id);
                    sb.append("\nBalance : " + balance);
                    sb.append("\nUsername : " + username);
                    sb.append("\n*******************\n");

                    System.out.println(sb);
                }
            }

            System.out.println("Successfully completed");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)
                    br.close();

            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}


Output

1| 1.11| Amzi
-------------

Id : 1
Balance : 1.11
Username :  Amzi
*******************

2| 3.33| Saiyad
-------------

Id : 2
Balance : 3.33
Username :  Saiyad
*******************

Successfully completed

1 comment:

  1. Try not to re-invent wheel when you need to fix common problems.

    As per the CSV file parsing task, you could use one of the best library uniVocity-parsers(http://www.univocity.com/pages/parsers-tutorial) with simplified API and excellent performance.
    In my project, it is used to parse CSV data more than 1GB+.

    Here is the code sample for reading csv data into list of arrays:

    private static void parseCSV() throws FileNotFoundException {
    CsvParser parser = new CsvParser(new CsvParserSettings());
    List parsedData = parser.parseAll(new FileReader("/examples/example.csv"));

    for (String[] row : parsedData) {
    StringBuilder strBuilder = new StringBuilder();
    for (String col : row) {
    strBuilder.append(col).append("\t");
    }
    System.out.println(strBuilder);
    }
    }

    ReplyDelete