■ 導入
* Gradle を使う
build.gradle
dependencies {
// opencsv
compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
}
■ サンプル
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.opencsv.CSVWriter;
public class Demo {
public static void main(String[] args) {
try {
// CSV出力
createCsv("sample.csv", new String[] { "Item1", "Item2", "Item3" },
Arrays.asList(new String[] { "1-1あ", "1-2い", "1-3う" }, new String[] { "2-1え", "2-2お", "2-3か" }));
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
System.out.println("Done!");
}
private static void createCsv(String csvFilePath, String[] csvHeaderItems, List<String[]> csvBodies)
throws FileNotFoundException, IOException {
List<String[]> csvContents = new ArrayList<>();
if (csvHeaderItems != null && csvHeaderItems.length > 0) {
csvContents = new ArrayList<>();
csvContents.add(csvHeaderItems);
csvContents.addAll(csvBodies);
} else {
csvContents = csvBodies;
}
try (FileOutputStream fileOutputStream = new FileOutputStream(csvFilePath)) {
// UTF-8 BOM付き(ExcelでCSV(UTF-8)を開くと文字化けするので、その対策)
// 参考文献:http://javatechnology.net/java/utf8-file-bom/ ★下記「補足」も 参照★
fileOutputStream.write(0xef);
fileOutputStream.write(0xbb);
fileOutputStream.write(0xbf);
try (CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(fileOutputStream, "UTF-8"));) {
csvWriter.writeAll(csvContents);
}
}
}
}
出力結果
sample.csv
"Item1","Item2","Item3"
"1-1あ","1-2い","1-3う"
"2-1え","2-2お","2-3か"