How to Write to a CSV File in Java

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(","));
}Copy

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\"" });Copy

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());
}Copy

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 (escapedData.contains(",") || escapedData.contains("\"") || escapedData.contains("'")) {
        escapedData = escapedData.replace("\"", "\"\"");
        escapedData = "\"" + escapedData + "\"";
    }
    return escapedData;
}Copy

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.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值