# How to read and write CSV files using core Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Sep 29, 2019, updated Sep 24, 2022. Topics: Java, CSV.
Canonical URL: https://attacomsian.com/blog/read-write-csv-files-core-java

> Learn how to read and write CSV files by using core Java APIs like the Scanner class or the BufferedReader class.

In earlier articles, I explained how to read and writing CSV files using [OpenCSV](https://attacomsian.com/blog/read-write-csv-files-opencsv) as well as [Apache Commons CSV](https://attacomsian.com/blog/read-write-csv-files-apache-commons-csv) library. 

This article is the last one in our short series to learn about 3rd-party libraries and core Java APIs for efficiently reading and writing CSV files.

A CSV file is 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 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](https://tools.ietf.org/html/rfc4180), 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 **use a 3rd-party library** like [OpenCSV](https://attacomsian.com/blog/read-write-csv-files-opencsv) for reading the CSV file. 

Third-party libraries are definitely a better choice 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:

<p class="file-desc"><span>users.csv</span></p>

```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](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html) 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.

```java
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:

```plaintext
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](https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html) class and the [String.split()](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split%28java.lang.String%29) method:

```java
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](https://attacomsian.com/blog/how-to-read-a-file-line-by-line-in-java) 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 the CSV file row. 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 like writing to any other text file in Java. The simplest way is to use the [FileWriter](https://docs.oracle.com/javase/8/docs/api/java/io/FileWriter.html) 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:

```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:

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

## Conclusion

In this tutorial, we 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:

* [Reading and writing CSV files using OpenCSV](https://attacomsian.com/blog/read-write-csv-files-opencsv)
* [Reading and writing CSV files using Apache Commons CSV](https://attacomsian.com/blog/read-write-csv-files-apache-commons-csv)
* [Export & Download Data as CSV File in Spring Boot](https://attacomsian.com/blog/export-download-data-csv-file-spring-boot)
