CSV格式:
它可以用excel打开,如果用记事本打开,会发现它是一种使用逗号(",")作为不同列之间的分隔符.
读取CSV格式:
import java.io.*;
/**
* 使用例子:
* CSVReader reader = new CSVReader("D:\\114.csv");
* String str1 = reader.readLine();//得到第一行
* String str2 = reader.readLine();//得到第二行
*/
public class CSVReader {
BufferedReader reader;
public String readLine() throws IOException {
return reader.readLine();
}
public CSVReader(String pathname) throws FileNotFoundException {
this.reader = new BufferedReader(new FileReader(new File(pathname)));
}
}
写入CSV格式:
import java.io.*;
/**
* 使用例子
* CSVWriter writer = new CSVWriter("D:\\114.csv");
* writer.write(new String[]{"a", "b", "c"});//第一行写入 a b c
* writer.write(new String[]{"d", "e", "f"});//第二行写入 d e f
*/
public class CSVWriter {
private BufferedWriter writer;
public void write(String[] writeStrings) throws IOException {
for (String str : writeStrings) {
writer.append(str + ",");
}
writer.append("\r");
writer.flush();
}
public CSVWriter(String writePath) throws FileNotFoundException, UnsupportedEncodingException {
this.writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(writePath)), "GBK"));
}
}