3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

opencsvでcsvファイル出力

Posted at

いっちばん単純な形。
このままの形で使うことは無いと思いますがベースにはできるかな?

opencsv.jarのバージョン4.0、javaのバージョンは1.7です。

CsvOutput.java
package com.test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.opencsv.CSVWriter;

public class CsvOutput {

	public static void main(String[] args) throws IOException {

		CSVWriter csvw = null;
		try {
            //インスタンス生成
			csvw = new CSVWriter(
	               new FileWriter(new File("c:\\test", "test.csv"))
	                , ",".charAt(0)
	                , "\"".charAt(0)
	                , "\"".charAt(0)
	                , "\r\n");
            //Stringの配列が1行分のデータになる
	        List<String[]> outStrList = new ArrayList<String[]>();
            //配列の数には項目数を定義
            //実際はこんな風にべた書きはしないと思うけど・・・
	        String[] outStr = new String[2];
	        outStr[0] = "酒を飲み過ぎ";
	        outStr[1] = "ゲロを吐く";
	        outStrList.add(outStr);

	        //書込み
	        csvw.writeAll(outStrList);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
                        // 最後はクローズする
			if (csvw != null) {
				csvw.close();
			}
		}
	}
}

・出力結果

test.csv
・出力ファイル内容
"酒を飲み過ぎ","ゲロを吐く"
3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?