How to load data from CSV file in Java - Example

You can load data from a CSV file in Java program by using BufferedReader class from java.io package. You can read the file line by line and convert each line into an object representing that data. Actually there are couple of ways to read or parse CSV file in Java e.g. you can use a third party library like Apache commons CSV or you can use Scanner class, but in this example we will use traditional way of loading CSV file using BufferedReader.


Here are the steps to load data from CSV file in Java without using any third party library :
  • Open CSV file using FileReader object
  • Create BufferedReader from FileReader
  • Read file line by line using readLine() method
  • Split each line on comma to get an array of attributes using String.split() method
  • Create object of Book class from String array using new Book()
  • Add those object into ArrayList using add() method
  • Return the List of books to caller


And here is our sample CSV file which contains details of my favorite books. It's called books.csv, each row represent a book with title, price and author information. First column is title of book, second column is price and third column is author of the book.
Effective Java,42,Joshua Bloch
Head First Java,39,Kathy Sierra
Head First Design Pattern,44,Kathy Sierra
Introduction to Algorithm,72,Thomas Cormen



Step by Step guide to load a CSV file in Java

Let's go through each steps to find out what they are doing and how they are doing :

Reading the File
To read the CSV file we are going to use a BufferedReader in combination with a FileReader. FileReader is used to read a text file in platform's default character encoding, if your file is encoded in other character encoding then you should use InputStreamReader instead of FileReader class. We will read one line at a time from the file using readLine() method until the EOF (end of file) is reached, in that case readLine() will return a null.


Split comma separated String
We take the string that we read from CSV file and split it up using the comma as the 'delimiter' (because its a CSV file). This creates an array with the all the columns of CSV file as we want, however values are still in Strings, so we need to convert them into proper type e.g. prices into float type as discussed in my post how to convert String to float in Java. Once we got all the attribute values, we create an object of Book class by invoking constructor of book as new Book() and pass all those attributes. Once we Book object then we simply add them to our ArrayList.

How to load CSV file in Java using BufferedReader


Java Program to load data from CSV file

Here is our full program to read a CSV file in Java using BufferedReader. It's good example of how to read data from file line by line, split string using a delimiter and how to create object from a String array in Java. Once you load data into program you can insert into database, or you can persist into some other format or you can send it over network to other JVM.

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * Simple Java program to read CSV file in Java. In this program we will read
 * list of books stored in CSV file as comma separated values.
 * 
 * @author WINDOWS 8
 *
 */
public class CSVReaderInJava {

    public static void main(String... args) {
        List<Book> books = readBooksFromCSV("books.txt");

        // let's print all the person read from CSV file
        for (Book b : books) {
            System.out.println(b);
        }
    }

    private static List<Book> readBooksFromCSV(String fileName) {
        List<Book> books = new ArrayList<>();
        Path pathToFile = Paths.get(fileName);

        // create an instance of BufferedReader
        // using try with resource, Java 7 feature to close resources
        try (BufferedReader br = Files.newBufferedReader(pathToFile,
                StandardCharsets.US_ASCII)) {

            // read the first line from the text file
            String line = br.readLine();

            // loop until all lines are read
            while (line != null) {

                // use string.split to load a string array with the values from
                // each line of
                // the file, using a comma as the delimiter
                String[] attributes = line.split(",");

                Book book = createBook(attributes);

                // adding book into ArrayList
                books.add(book);

                // read next line before looping
                // if end of file reached, line would be null
                line = br.readLine();
            }

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

        return books;
    }

    private static Book createBook(String[] metadata) {
        String name = metadata[0];
        int price = Integer.parseInt(metadata[1]);
        String author = metadata[2];

        // create and return book of this metadata
        return new Book(name, price, author);
    }

}

class Book {
    private String name;
    private int price;
    private String author;

    public Book(String name, int price, String author) {
        this.name = name;
        this.price = price;
        this.author = author;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    @Override
    public String toString() {
        return "Book [name=" + name + ", price=" + price + ", author=" + author
                + "]";
    }

}

Output
Book [name=Effective Java, price=42, author=Joshua Bloch]
Book [name=Head First Java, price=39, author=Kathy Sierra]
Book [name=Head First Design Pattern, price=44, author=Kathy Sierra]
Book [name=Introduction to Algorithm, price=72, author=Thomas Cormen]


That's all about how to load CSV file in Java without using any third party library.  You have learned how to use BufferedReader to read data from CSV file and then how to split comma separated String into String array by using String.split() method. Though you can do it even more easily by using third party library like Apache commons CSV, but knowing how to do it using pure Java will help you to learn key classes form JDK. 


If you like this tutorial and interested to learn more about how to deal with files and directory in Java, you can checkout following Java IO tutorial :
  • How to read Excel File in Java using Apache POI? [example]
  • How to append data into an existing file in Java? [example]
  • 2 ways to read a file in Java? [tutorial]
  • How to create a file or directory in Java? [example]
  • How to read a text file using Scanner class in Java? [answer]
  • How to write content into file using BufferedWriter class in Java? [example]
  • How to read username and password from command line in Java? [example]
  • How to read Date and String from Excel file in Java? [tutorial]


No comments:

Post a Comment