データをCSVファイルにエクスポートする方法 – Java

Comma-Separated Values(CSV)
ファイルは通常のプレーンテキストファイルで、列単位でデータを格納し、セパレータ(カンマ)で分割します。 。
このチュートリアルでは、データやオブジェクトを簡単にCVSファイルに書き込むための簡単な `CVSUtils`クラスを紹介します。
1. CSVライティングの例
1.1次の `CVSUtils`クラスを見直し、カスタムセパレータ、カスタム囲み引用符(デフォルトは空)、二重引用符を別の二重引用符でエスケープします(https://tools.ietf.org/html/rfc4180[RFC4180])。
CSVUtils.java
package com.mkyong.utils;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
public class CSVUtils {
private static final char DEFAULT__SEPARATOR = ',';
public static void writeLine(Writer w, List<String> values) throws IOException {
writeLine(w, values, DEFAULT__SEPARATOR, ' ');
}
public static void writeLine(Writer w, List<String> values, char separators) throws IOException {
writeLine(w, values, separators, ' ');
}
//https://tools.ietf.org/html/rfc4180
private static String followCVSformat(String value) {
String result = value;
if (result.contains("\"")) {
result = result.replace("\"", "\"\"");
}
return result;
}
public static void writeLine(Writer w, List<String> values, char separators, char customQuote) throws IOException {
boolean first = true;
//default customQuote is empty
if (separators == ' ') {
separators = DEFAULT__SEPARATOR;
}
StringBuilder sb = new StringBuilder();
for (String value : values) {
if (!first) {
sb.append(separators);
}
if (customQuote == ' ') {
sb.append(followCVSformat(value));
} else {
sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
}
first = false;
}
sb.append("\n");
w.append(sb.toString());
}
}
1.2 `CSVUtils`の使い方を示す例。
CSVUtils.java
package com.mkyong.utils;
import java.io.FileWriter;
import java.util.Arrays;
public class CVSUtilExample {
public static void main(String[]args) throws Exception {
String csvFile = "/Users/mkyong/csv/abc.csv";
FileWriter writer = new FileWriter(csvFile);
CSVUtils.writeLine(writer, Arrays.asList("a", "b", "c", "d"));
//custom separator + quote
CSVUtils.writeLine(writer, Arrays.asList("aaa", "bb,b", "cc,c"), ',', '"');
//custom separator + quote
CSVUtils.writeLine(writer, Arrays.asList("aaa", "bbb", "cc,c"), '|', '\'');
//double-quotes
CSVUtils.writeLine(writer, Arrays.asList("aaa", "bbb", "cc\"c"));
writer.flush();
writer.close();
}
}
出力
/Users/mkyong/csv/abc.csv
a,b,c,d "aaa","bb,b","cc,c" 'aaa'|'bbb'|'cc,c' aaa,bbb,cc""c
2.その他の例
別の例を見てみましょう。オブジェクトのリストを作成し、それをCSVファイルに書き出します。
2.1開発者クラス。
Developer.java
package com.mkyong.csv;
import java.math.BigDecimal;
public class Developer {
private String name;
private BigDecimal salary;
private int age;
public Developer(String name, BigDecimal salary, int age) {
this.name = name;
this.salary = salary;
this.age = age;
}
//...
}
2.2例。
CVSUtilExample.java
package com.mkyong.utils;
import com.mkyong.java8.Developer;
import java.io.FileWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CVSUtilExample {
public static void main(String[]args) throws Exception {
String csvFile = "/Users/mkyong/csv/developer.csv";
FileWriter writer = new FileWriter(csvFile);
List<Developer> developers = Arrays.asList(
new Developer("mkyong", new BigDecimal(120500), 32),
new Developer("zilap", new BigDecimal(150099), 5),
new Developer("ultraman", new BigDecimal(99999), 99)
);
//for header
CSVUtils.writeLine(writer, Arrays.asList("Name", "Salary", "Age"));
for (Developer d : developers) {
List<String> list = new ArrayList<>();
list.add(d.getName());
list.add(d.getSalary().toString());
list.add(String.valueOf(d.getAge()));
CSVUtils.writeLine(writer, list);
//try custom separator and quote.
//CSVUtils.writeLine(writer, list, '|', '\"');
}
writer.flush();
writer.close();
}
}
出力
/Users/mkyong/csv/developer.csv
Name,Salary,Age mkyong,120500,32 zilap,150099,5 ultraman,99999,99
-
注** 自分で実装するのがまだ難しい場合は、このサードパーティのCSVライブラリhttp://opencsv.sourceforge.net/[OpenCSV]をお試しください。
完了しました。
参考文献
-
http://ostermiller.org/utils/CSV.html
[Ostermiller Javaユーティリティ –
カンマ区切り値(CSV)]。
https://tools.ietf.org/html/rfc4180
[RFC4180 – のフォーマット
カンマ区切り値(CSV)]。
OpenCSVウェブサイト
-
link://java/how-to-read-and-parse-csv-file-in-java/[CSVをパースする方法
Javaのファイル]。
http://en.wikipedia.org/wiki/Comma-separated__values
[ウィキペディア –
カンマ区切り値(CSV)]