In earlier articles, I explained how to read and writing CSV files 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 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:
- 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
- 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 use a 3rd-party library like 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:
- Using the
Scanner
Class - Using
BufferedReader
andString.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 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 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, 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
- Reading and writing CSV files using Apache Commons CSV
- Export & Download Data as CSV File in Spring Boot
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.