Skip to main content

How to load data from CSV file in Java

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]


Read more: http://www.java67.com/2015/08/how-to-load-data-from-csv-file-in-java.html#ixzz4b0kTcNIz

Comments

Popular posts from this blog

Mockito interview Questions

1.       Question 1. What Is Mockito? Answer : Mockito allows creation of mock object for the purpose of Test Driven Development and Behavior Driven development. Unlike creating actual object, Mockito allows creation of fake object (external dependencies) which allows it to give consistent results to a given invocation. 2.       Question 2. Why Do We Need Mockito? What Are The Advantages? Answer : Mockito differentiates itself from the other testing framework by removing the expectation beforehand. So, by doing this, it reduces the coupling. Most of the testing framework works on the "expect-run-verify". Mockito allows it to make it "run-verify" framework. Mockito also provides annotation which allows to reduce the boilerplate code. 3.       Question 3. Can You Explain A Mockito Framework? Answer : In Mockito, you always check a particular class. The dependency in that class is injected using mock object. So, for example, if you have service class

JAVA Expert Interview Questions Answers 2017

Java Basics ::  Interview Questions and Answers Home  »  Interview Questions  »  Technical Interview  »  Java Basics  » Interview Questions 1.     What is the difference between a constructor and a method? A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator. 2.     What is the purpose of garbage collection in Java, and when is it used? The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. 3.     Describe synchronization in respect to multithreading. With respect to

Java Example Program to Convert List to Set

import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class ListToSet {  /**   * @author Amarjit Kumar   * @category interview questions   *   * Description: Convert List to set in java with example program   *   */  public static void main(String[] args) {   ArrayList<String> arrList= new ArrayList<>();   arrList.add("Java");   arrList.add("Java");   arrList.add("List to String");   arrList.add("Example Program");   Set<String> strSet = new HashSet<String>(arrList);   System.out.println(strSet);   System.out.println(arrList);  } } /*  * Java program to convert list to set. Convert ArrayList of string to HashSet  * in java example program How to convert List to Set in java Set<String> strSet  * = new HashSet<String>(arrList); HashSet having a constructor which will take  * list as an argument. Lets see how to convert list to Set using java program.