1. Overview
In this brief tutorial, we’re going to learn how to write to a CSV file using Java. CSV stands for Comma-Separated-Values and it’s a common format for doing a bulk data transfer 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 next 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\"" });
And 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 let’s look now 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 whitespace.
Which characters are a problem 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) { 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
4. Conclusion
In this quick article, we showed 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.