package com.xxq.qianniu.rest.util;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
/**
* @author xq
* @since 2013-05-20
* @version 1.0
*/
public class CsvUtil {
private static final String FILE = "C:/Users/Administrator/Desktop/test.csv";
public static void writerCsvFile(String fileName, List<String[]> content) throws IOException {
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(fileName), Charset.forName("GBK"));
CSVWriter writer = new CSVWriter(out,',',CSVWriter.NO_QUOTE_CHARACTER);
writer.writeAll(content);
writer.close();
}
public static void writerCsvFile(File file, List<String[]> content) throws IOException {
if (!file.exists()) {
file.createNewFile();
}
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("GBK"));
CSVWriter writer = new CSVWriter(out,',',CSVWriter.NO_QUOTE_CHARACTER);
writer.writeAll(content);
writer.close();
}
public static List<String[]> readCsvFile(String fileName) throws IOException {
File file = new File(fileName);
if (!file.exists()) {
throw new IOException("file not exist, fileName = " + fileName);
}
InputStreamReader in = new InputStreamReader(new FileInputStream(fileName), Charset.forName("GBK"));
CSVReader reader = new CSVReader(in);
List<String[]> lines = reader.readAll();
reader.close();
return lines;
}
public static List<String[]> readCsvFile(File file) throws IOException {
if (!file.exists()) {
throw new IOException("file not exist, fileName = " + file.getAbsolutePath());
}
InputStreamReader in = new InputStreamReader(new FileInputStream(file), Charset.forName("GBK"));
CSVReader reader = new CSVReader(in);
List<String[]> lines = reader.readAll();
reader.close();
return lines;
}
public static List<String[]> readCsvFile(byte[] file) throws IOException {
InputStreamReader in = new InputStreamReader(new ByteArrayInputStream(file), Charset.forName("GBK"));
CSVReader reader = new CSVReader(in);
List<String[]> lines = reader.readAll();
reader.close();
return lines;
}
public static void main(String[] args) throws IOException {
List<String[]> content = new ArrayList<String[]>();
content.add("你,我,他,她,它".split(","));
content.add("you,me,he,she,it".split(","));
content.add("1,2,3,4,5".split(","));
writerCsvFile(FILE, content);
List<String[]> content2 = readCsvFile(FILE);
for (String[] line : content2) {
for (String field : line) {
System.out.print(field);
System.out.print(",");
}
System.out.println("");
}
}
}