1. Overview
In this quick tutorial, we’ll learn how to write to a CSV file using Java. CSV stands for Comma-Separated-Values, and it’s a common format for bulk data transfers between systems.
To write our CSV file, we’ll be using classes in the java.io package.
We’ll talk about special characters and how to handle them. We’ll be targeting our output file to open in Microsoft Excel and Google Sheets.
After our Java example, we’ll take a brief look at some available third-party libraries for working with CSV files.
2. Writing With PrintWriter
We’re going to use a PrintWriter for writing our CSV file. For a more detailed look at using java.io to write to a file, see our article on writing to files.
2.1. Writing the CSV
First, let’s create a method for formatting a single line of data represented as an array of Strings:
public String convertToCSV(String[] data) {
return Stream.of(data)
.map(this::escapeSpecialCharacters)
.collect(Collectors.joining(","));
}
Before we call this method though, let’s build up some example data:
List<String[]> dataLines = new ArrayList<>();
dataLines.add(new String[]
{ "John", "Doe", "38", "Comment Data\nAnother line of comment data" });
dataLines.add(new String[]
{ "Jane", "Doe, Jr.", "19", "She said \"I'm being quoted\"" });
With that data in hand, let’s convert each row with convertToCSV, and write it to a file:
public void givenDataArray_whenConvertToCSV_thenOutputCreated() throws IOException {
File csvOutputFile = new File(CSV_FILE_NAME);
try (PrintWriter pw = new PrintWriter(csvOutputFile)) {
dataLines.stream()
.map(this::convertToCSV)
.forEach(pw::println);
}
assertTrue(csvOutputFile.exists());
}
2.2. Handling Special Characters
In a CSV file, certain characters are problematic, and as developers, we rarely have total control over the quality of our data. So now let’s look at how to handle special characters.
For our example, we’ll focus on commas, quotes, and new lines. Fields containing commas or quotes will be surrounded by double quotes, and double quotes will be escaped with double quotes. We’ll eliminate new lines and replace them each with white space.
Problematic characters and how they should be handled may vary with the use case.
Our convertToCSV method calls the escapeSpecialCharacters method on each piece of data as it’s building up a String.
Let’s implement our escapeSpecialCharacters method now:
public String escapeSpecialCharacters(String data) {
if (data == null) {
throw new IllegalArgumentException("Input data cannot be null");
}
String escapedData = data.replaceAll("\\R", " ");
if (data.contains(",") || data.contains("\"") || data.contains("'")) {
data = data.replace("\"", "\"\"");
escapedData = "\"" + data + "\"";
}
return escapedData;
}
3. Third-Party Libraries
As we saw with our example, writing a CSV file can become complicated when we start thinking about special characters and how to handle them.
Luckily for us, there are many third-party libraries available for working with CSV files, and many of them handle these special characters and other exceptional cases that may occur.
Let’s take a look at a few of them:
- Apache Commons CSV: Apache’s CSV offering for working with CSV Files
- Open CSV: Another popular and actively-maintained CSV library
- Flatpack: An open-source CSV library being actively developed
- CSVeed: Open-source and actively-maintained
- FastCSV – High-performance open-source library
4. Conclusion
In this brief article, we discussed how to write a CSV file using Java’s PrintWriter class. Next, we discussed and handled special characters in the data being output.
After our plain Java example, we looked at an overview of available third-party libraries.
The example code is available over on GitHub.