In earlier articles, I have written about reading and writing CSV files by using OpenCSV as well as Apache Commons CSV library. This article is the last one in our short series to learn about 3rd-party libraries as well as core Java APIs for efficiently reading and writing CSV files.

A CSV file is just a plain-text file that stores data in a tabular format, where columns are separated by a delimiter (usually a comma , or a tab). These files are a common choice for importing and exporting data between different servers and applications.

In this article, you'll learn how to read and write CSV files using core Java without using any 3rd-party library.

Two important problems that we may face while reading and parsing CSV files:

  1. The field value contains the delimiter. For example, a comma is used as a separator, and the field value containing commas: 1, "Greta, Jones", UK
  2. The field value contains double-quotes, and the double-quotes are used to wrap field values. In such a case, according to RFC 4180, a double-quote that appears inside the field value must be properly escaped by preceding it with another double-quote: "1", "Greta""Jones", "UK"

If your CSV file contains any of the above things, you should rather use a 3rd-party library like OpenCSV for reading the CSV file. Third-party libraries are definitely good for handling different CSV formats, delimiters, and special characters.

However, not all CSV files have such problems. For simple CSV files (without double-quotes and delimiters in field values), core Java is sufficient.

Reading CSV Files in Core Java

In Java, there are multiple ways of reading and parsing CSV files. We will discuss the following two ways of doing so:

  1. Using the Scanner Class
  2. Using BufferedReader and String.split() Method

Here is how our sample CSV file looks:

users.csv

1,John Deo,john@example.com,US
2,Alex Jones,alex@example.com,DE
3,Jovan Lee,jovan@example.com,FR
4,Greg Hover,greg@example.com,US
4,Emma Watson,emma@example.com,CA

1. Using Scanner Class

The Scanner class in Java breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

try {
    // create scanner instance
    Scanner scanner = new Scanner(Paths.get("users.csv").toFile());

    // set comma as delimiter
    scanner.useDelimiter(",");

    // read all fields
    while (scanner.hasNext()) {
        System.out.print(scanner.next() + " ");
    }

    //close the scanner
    scanner.close();

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

You'll see the following output:

1 John Deo john@example.com US
2 Alex Jones alex@example.com DE
3 Jovan Lee jovan@example.com FR
4 Greg Hover greg@example.com US
4 Emma Watson emma@example.com CA 

2. Using BufferedReader and String.split() Method

Another way of reading and parsing a CSV file is by using a combination of the BufferedReader class and the String.split() method:

try {
    // CSV file delimiter
    String DELIMITER = ",";

    // create a reader
    BufferedReader br = Files.newBufferedReader(Paths.get("users.csv"));

    // read the file line by line
    String line;
    while ((line = br.readLine()) != null) {
        // convert line into tokens
        String[] tokens = line.split(DELIMITER);

        // TODO: do something here with the data

        // print all tokens
        for (String token : tokens) {
            System.out.println(token);
        }
    }

    // close the reader
    br.close();

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

In the example above, we are doing the following:

  • Open the CSV file for reading by using the Files.newBufferedReader() method.
  • Create an instance of BufferedReader to read the file line by line until the end of file (EOF) is reached.
  • Use the String.split() method to convert each line into multiple tokens by using the comma (,) as a delimiter.
  • The tokens array should contain a list of fields found in each row of the CSV file. You should use this array to process the CSV record; like saving it to a database or storing in a Java collection for later use.

Writing CSV Files in Core Java

Writing data to a CSV file is just like writing to any other text file in Java. The simplest way is to use the FileWriter class. This is a convenience class for writing streams of characters.

The following example demonstrates how to write a List of objects to a CSV file using the FileWriter in Java:

try {
    // create a list of objects
    List<List<String>> records = Arrays.asList(
            Arrays.asList("1", "John Lee", "US"),
            Arrays.asList("2", "Jovan Roover", "DE"),
            Arrays.asList("3", "Emma Watson", "UK")
    );

    // create a writer
    BufferedWriter writer = Files.newBufferedWriter(Paths.get("users-with-header.csv"));

    // write header record
    writer.write("ID,Name,Country");
    writer.newLine();

    // write all records
    for (List<String> record : records) {
        writer.write(String.join(",", record));
        writer.newLine();
    }

    //close the writer
    writer.close();

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

Here is how the newly created CSV file looks like:

ID,Name,Country
1,John Lee,US
2,Jovan Roover,DE
3,Emma Watson,UK

Conclusion

In this tutorial, you have learned how to read and write CSV files using core Java without any 3rd-party library. You can use either the Scanner class or BufferedReader to read and parse a CSV file line by line. For writing to CSV files, you should use the FileWriter class.

This solution is intended for reading and writing simple CSV files. For complex CSV files with multiple delimiters, double-quotes, and special characters, you should use 3rd-party libraries.

Further Reading

If you enjoy reading this article, you may also be interested in reading other CSV related articles:

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.