Tbpgr Blog

Recruiting Operations tbpgr(てぃーびー) のブログ

Java | opencsvでCSVファイルを操作する(tsv対応版)

概要

opencsvでCSVファイルを操作する(tsv対応版)

詳細

下記の記事のTSV対応版サンプルを作成。

Java | opencsvでCSVファイルを操作する
http://d.hatena.ne.jp/tbpg/20130514/1368543588

サンプルコード

package opencsv;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Arrays;
import java.util.List;

import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;

public class SampleOpenCSV {
  private static final String UTF_8 = "UTF-8";

  public static void main(String[] args) throws IOException {
    readCsv(',', "abc,def\nhij,klm");
    readCsv(',', "abc\tdef\nhij\tklm");
    writeCsv(',', "csv");
    writeCsv('\t', "tsv");
  }

  private static void readCsv(char separator, String input) throws UnsupportedEncodingException, IOException {
    input = "abc,def\nhij,klm";
    byte[] buf = input.getBytes(UTF_8);

    InputStream byteIn = new ByteArrayInputStream(buf);
    InputStreamReader in = new InputStreamReader(byteIn, UTF_8);
    CSVReader csvReader = new CSVReader(in, separator);

    List<String[]> lines = csvReader.readAll();
    for (String[] strings : lines) {
      for (String string : strings) {
        System.out.print(string + ",");
      }
      System.out.println("");
    }
    csvReader.close();
  }

  private static void writeCsv(char separator, String extension) throws UnsupportedEncodingException, IOException {
    List<String[]> csv = Arrays.asList(new String[] {"1", "2"}, new String[] {"3", "4"});

    FileOutputStream out = new FileOutputStream("opencsv." + extension);
    Writer writer = new OutputStreamWriter(out);
    CSVWriter csvWriter = new CSVWriter(writer, separator);
    csvWriter.writeAll(csv);

    csvWriter.close();
    writer.close();
    out.close();
  }
}

出力

abc,def,
hij,klm,
abc,def,
hij,klm,

出力ファイル

$cat opencsv.csv
"1","2"
"3","4"
$cat opencsv.tsv
"1"	"2"
"3"	"4"