2
0

More than 1 year has passed since last update.

シンプルな CSV ファイル書き出し Javaサンプル (Apache commons-csv を利用)

Last updated at Posted at 2021-11-17

ちょっと CSV ファイルを書き出す Java プログラミングを実装したい場合に役立ちそうなサンプルをメモしておきます。
CSVファイル読み書きには RFC 4180 を実装する必要がありますが、一般的にはライブラリ利用により実現します。
この例では Apache commons-csv を利用した CSVファイル書き出しサンプル記述を残しておきます。

Maven (pom.xml)

まず最初に、CSV ファイル書き出しを実現するためのライブラリである Apache commons-csv をビルドに組み込みます。 pom.xml ファイルの <dependencies> に以下の Maven Repository 記述を追加します。 (ビルドでの自動ダウンロードの実現のためには、インターネットに接続されている必要があります)

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.9.0</version>
</dependency>

なお、Maven Repos 上の commons-csv はこちらを参照してください。

Java コード

commons-csv が利用可能になったので、早速これを Java で利用して CSVファイル書き出しを実行するコードを記述しましょう。

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.QuoteMode;

public class App {
    public static void main(String[] args) throws IOException {
        // RFC4180 を基準に、数字以外はダブルクオートで囲む仕様のCSV書式を作成.
        final CSVFormat.Builder formatBuilder = CSVFormat.RFC4180.builder();
        formatBuilder.setQuoteMode(QuoteMode.NON_NUMERIC);
        final CSVFormat format = formatBuilder.build();

        // CSV出力をおこなう CSVPrinter クラスのインスタンスを作成.
        try (CSVPrinter printer = new CSVPrinter(new BufferedWriter( //
                new OutputStreamWriter(new FileOutputStream( //
                        "./target/output.csv"), "Windows-31J")),
                format)) {

            // CSVヘッダーを出力.
            printer.print("Name");
            printer.print("Age");
            printer.print("Address");
            printer.println();

            // CSVデータ その1 を出力.
            printer.print("Taro Tanaka");
            printer.print(12);
            printer.print("Tokyo, Otemachi.");
            printer.println();

            // CSVデータ その2 を出力.
            printer.print("Hanako Yamada");
            printer.print(14);
            printer.print("Shibuya, \"Hatchi\".");
            printer.println();
        }
    }
}

簡易な解説

  • RFC4180 を基準に、数字以外はダブルクオートで囲む仕様のCSV書式を作成.
  • CSV出力をおこなう CSVPrinter クラスのインスタンスを作成.
  • CSVヘッダーを出力.
  • CSVデータ その1 を出力.
  • CSVデータ その2 を出力.

ピンポイント

デフォルトの挙動だと、一般的に目にするCSVファイルは生成されません。普通の CSVファイルを生成するためには、以下の記述が必要でした。

final CSVFormat.Builder formatBuilder = CSVFormat.RFC4180.builder();
formatBuilder.setQuoteMode(QuoteMode.NON_NUMERIC);
final CSVFormat format = formatBuilder.build();

文書情報

  • 初出: 2021-11-17

関連情報

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0