Monday, September 2, 2024

How to read CSV file in Java without using a third-party library? FileReader Example Tutorial

Hello guys, as you learn Java, one thing that comes up early and often is reading from/ writing to files, and doing something useful with that data. This is also one thing which you will keep doing and also forgetting very soon, if you are not then you have good memory as I always forget it and then I do google search to find my own articles. If you read this blog then you know that in the past, I have shared how to load CSV file using OpenCSV library as well how to load a CSV file with header using Jackson but a lot of you asked me how to do this without using any third party library like Jackson or OpenCSV. So, I thought to write about this article and I actually written but forgot to publish it for a long time. But I today I found it and publishing it now, it still works well. 

In this Java CSV Reader example we will:
  • Read data from a CSV text file.
  • Parse that data into several different data types.
  • Load the data into an object.
  • Load those objects into an ArrayList.
  • Display them and do a simple calculation.

Data for a program is often stored in different types of file formats, with one of the simplest being CSV, a format using .txt files where each data item is simply separated by commas and put on different lines.


How to parse a CSV file without using any third party library in Java like OpenCSV

Now, let's see how to read a  CSV file in Java but before that here we have a sample inventory file, with the data in the order item, quantity, price

persons.txt
Robin,31,NewYork
Tim,32,Paris
Stuwart,33,London
Craig,34,Tokyo


you can see that the file doesn't have a header but if it does, you need to ignore the header, the first line. 

How to read CSV file in Java without using a third-party library? FileReader Example Tutorial



We will first create a Person class in Java to represent each line in CSV file.

class Person {
    private String name;
    private int age;
    private String city;

    public Person(String name, int age, String city) {
        super();
        this.name = name;
        this.age = age;
        this.city = city;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getCity() {
        return city;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", city=" + city + "]";
    }

}
 


Reading the CSV File

To read the file we are going to be using a BufferedReader in combination with a FileReader.

We will read one line at a time from the file using readLine() until the End Of File is reached (readLine will return a null)

String.split()

We take the string that we read and split it up using the comma as the 'delimiter' (the character that tells the function when to start a new word and is discarded). This creates an array with the data we want, however still in Strings, so we need to convert the values that are not supposed to be strings into the proper values, using Integer.parseInt() and Float.parseFloat()

We pass those values to the constructor for our Inventory object, and then simply add that object to our ArrayList.

The full program: (save in same directory as others as FileFunctions.java)


Sample Code 

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Simple Java program to parse CSV file in Java.
 * @author WINDOWS 8
 *
 */
public class CSVReader {

    public static void main(String... args) {
        List<Person> people = load("persons.txt");
        
        // let's print all the person read from CSV file
        for(Person p: people){
            System.out.println(p);
        }
    }

    /**
     * Java Method to read CSV file without using third party library
     * @param path to CSV file
     * @return list of Person loaded from CSV file
     */
    public static List<Person> load(String path) {
        // create ArrayList to store Person objects
        List<Person> persons = new ArrayList<>();
        try {
            // create a BufferedReader instance with a FileReader
            BufferedReader br = new BufferedReader(
                    new FileReader("persons.txt"));

            // reading first line from CSV file
            String line = br.readLine();

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

                // using split method to split line into individual fields
                String[] fields = line.split(",");

                // file format is String, int and String
                String name = fields[0];
                int age = Integer.parseInt(fields[1]);
                String city = fields[2];

                // creating Person object from CSV file contents
                Person temp = new Person(name, age, city);

                // add object to array list
                persons.add(temp);

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

            // close BufferedReader, release file descriptor
            br.close();
            
        } catch (FileNotFoundException fe) {
            System.out.println("file : " + path + " not found");
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        return persons;
    }

}


Output

Person [name=Robin, age=31, city=NewYork]

Person [name=Tim, age=32, city=Paris]

Person [name=Stuwart, age=33, city=London]

Person [name=Craig, age=34, city=Tokyo]


You can see that how easy it is to read a CSV File in Java. It's no different than reading a text file if you use BufferedReader and FileReader correctly. But don't forget to close the file readers, you can also use try-with-resource so that they will be automatically closed once you are done with it. 

That's all about how to read CSV file in Java. If you ever need need to parse CSV file without using any third party library then you can use this solution and code. It's very simple, just read the CSV file line by line using FileReader and BufferedReader. It's really nice and easy and you can also save on dependency management. 

Other Java File tutorials you may like
  • How to check if a File is hidden in Java? (solution)
  • How to read JSON File in Java? (solution)
  • How to read an XML file in Java? (guide)
  • How to read an Excel file in Java? (guide)
  • How to read an XML file as String in Java? (example)
  • How to copy non-empty directories in Java? (example)
  • How to read/write from/to RandomAccessFile in Java? (tutorial)
  • How to append text to a File in Java? (solution)
  • How to read a ZIP file in Java? (tutorial)
  • How to read from a Memory Mapped file in Java? (example)

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.