All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Java Read CSV File Into Arraylist

Last Updated : Mar 11, 2024

Java Read CSV File Into Arraylist

In this article we will show you the solution of java read csv file into arraylist, by using the BufferedReader class from the java.io package, Java programs can load data from CSV files.

A line by line read of the file can be converted into a data object for each line of data.

As far as reading or parsing CSV files in Java is concerned, you have a couple of options, including using a third-party library like Apache commons CSV or using the Scanner class, but in this example we will use the traditional way of loading CSV files with a buffered reader.

We will now discuss the idea of how to read csv files into an arraylist in java with an example.

Step By Step Guide On Java Read CSV File Into Arraylist :-

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;
public class TalkersCodeCSV {
    public static void main(String... args) {
        List<Notes> notes = readNotesFromCSV("notes.txt");
        for (Notes n : notes) {
            System.out.println(n);
        }
    }
    private static List<Notes> readNotesFromCSV(String fileName) {
        List<Notes> notes = new ArrayList<>();
        Path pathToFile = Paths.get(fileName);
        try (BufferedReader br = Files.newBufferedReader(pathToFile,
                StandardCharsets.US_ASCII)) {
            String line = br.readLine();
            while (line != null) {
                String[] attributes = line.split(",");
                Notes notes = createNotes(attributes);
                notes.add(notes);
                line = br.readLine();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
return notes;
    }
    private static Notes createNotes(String[] metadata) {
        String name = metadata[0];
        int price = Integer.parseInt(metadata[1]);
        String author = metadata[2];
        return new Notes(name, price, author);
    }
}
class Notes {
    private String name;
    private int price;
    private String author;
    public Notes(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 "Notes [name=" + name + ", price=" + price + ", author=" + author
                + "]";
    }
}
  1. In the code, there is a class called TalkersCodeCSV, which contains a main method that reads data from a CSV file and stores it.
  2. Reading the data from the CSV file is performed through the readNotesFromCSV method in the main method.
  3. Using the readNotesFromCSV method, you can retrieve a list of Note objects by passing a filename as an input parameter.
  4. A Notes object is stored in an empty ArrayList created by the method.
  5. A Path object representing the location of the file is also created by this method.
  6. After this method has created a buffered reader object, the file will be read.
  7. Reading the file's first line is done via the readLine method of a BufferedReader object.
  8. In this program, the lines of the file are read using a while loop.
  9. By using the comma (",") as a delimiter, the split method splits each line into an array of strings.
  10. An array of strings is passed into the createNotes method when a Notes object is to be created.
  11. As a result, the Notes object has been added to the array list.
  12. In this loop, the next line of the file is read and the loop continues until all lines of the file have been read.
  13. Console messages are printed when an IOException occurs.
  14. You can read Notes objects from CSV using the readNotesFromCSV method.
  15. Notes objects are created by taking an array of strings as input and returning them as note objects.
  16. An array of strings is parsed in order to obtain the name, price, and author, and a Notes object is created accordingly.
  17. It is overridden so that it returns a string representation of the Notes object instead of the toString method of the Notes class.
  18. There is also a Notes class defined in the code that contains fields for the number, name, and author of a note set. These fields can be accessed and set through methods in the code.
  19. In the main method, each Notes object in the list is printed out using a for-each loop, and the println method is used to print them out.

Conclusion :-

As a result, we have successfully learned how to read csv files into an arraylist in java with an example.

The CSV format is used to store data delimited by commas (or semicolons in some cases).

CSV files contain records, each represented by a single line. BufferedReader or Scanner are simple ways to read data from basic CSV files.

It is possible, however, to not get the expected results when reading a more complicated CSV file. CSV files are most easily read using an external library such as OpenCSV.

I hope this article on java read csv file into arraylist helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Ashish

Ashish is a dynamic and motivated individual with a passion of programming and an experienced programmer having 3+ years of experience in various languages like Java, Python, HTML, CSS, JavaScript, jQuery and various frameworks like Bootstrap

Follow Ashish On Linkedin 🡪