Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:


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)

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)) {

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) {
    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 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.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Generic footer banner
Comments are closed on this article!