原文网站:http://ostermiller.org/utils/CSV.html
1、这是一个帮助读取和书写csv文件的工具类
CSV parser类关注点在于阅读csv文件:splitting out fields (even quoted and escaped fields), escaped data, line numbering, escape and comments.读取的结果:每一行转换为一个数组,每个单元也可以单独取出来
CSV printer类关注于如何写csv文件
该工具类支持两种csv文件格式:
UNIX 格式:
Microsoft Excel格式对于引号的转移字符(\"),换行(\n),反斜杠(\)
每一条记录属于一行,如果一个字段包含一个新的行,新的行必须被转义
空格在开始和结束字段中是被忽略的
与传统的Unix文件处理工具是兼容的
Reader: CSVParser, Writer: CSVPrinter
双引号转义字符,没有其他的
与其他的数据处理程序,有相同的格式输入,输出
空格在开始和结束字段中是被重视的
Reader: ExcelCSVParser, Writer: ExcelCSVPrinter
2、Labeled CSV Parser
csv文件的装饰类,用于读取csv文件表的表头,即列名,可以根据列名读入数据。LabeledCSVParser lcsvp = new LabeledCSVParser( new CSVParser( new StringReader( "Name,Phone\n" + "Stewart,212-555-3233\n" + "Cindy,212-555-8492\n" ) ) ); while(lcsvp.getLine() != null){ System.out.println( "Name: " + lcsvp.getValueByLabel("Name") ); System.out.println( "Phone: " + lcsvp.getValueByLabel("Phone") ); }
3、CSVParse (CSV Reader Interface)
两种格式读取的的公共接口
CSVPrint printer; // UNIX style printer = new CSVPrinter(System.out); // Microsoft Excel style printer = new ExcelCSVPrinter(System.out);
4、CSV Print(CSV Writer Interface)
两种格式输出的公共接口
CSVPrint printer; // UNIX style printer = new CSVPrinter(System.out); // Microsoft Excel style printer = new ExcelCSVPrinter(System.out);
5、CSV Printer (UNIX Style CSV Writer)
// Create the printer
CSVPrinter csvp = new CSVPrinter(
System.out
);
// Write to the printer
csvp.writeln(
new String[]{
// Create the printer CSVPrinter csvp = new CSVPrinter( System.out ); // Write to the printer csvp.writeln( new String[]{ "hello","world" } );
6、CSV Parser (UNIX Style CSV Reader)
// Parse the data String[][] values = CSVParser.parse( new StringReader( "hello,world\n" + "how,are,you" ) ); // Display the parsed data for (int i=0; i<values.length; i++){ for (int j=0; j<values[i].length; j++){ System.out.println(values[i][j]); } System.out.println("-----"); }
7、Excel CSV Printer (Microsoft Excel Style CSV Writer)
// Create the printer ExcelCSVPrinter ecsvp = new ExcelCSVPrinter( System.out ); // Write to the printer ecsvp.writeln( new String[]{ "hello","world" } );
8、Excel CSV Parser (Microsoft Excel Style CSV Reader)
// Parse the data String[][] values = ExcelCSVParser.parse( new StringReader( "hello,world\n" + "how,are,you" ) ); // Display the parsed data for (int i=0; i<values.length; i++){ for (int j=0; j<values[i].length; j++){ System.out.println(values[i][j]); } System.out.println("-----"); }
9、编码格式
如果csv文件里面的编码格式,速写出来出现乱码
CSVParser shredder = new CSVParser( new InputStreamReader( new FileInputStream("CSVCharsetTest.gb2312csv"), "GB2312" ) ); String t; while ((t = shredder.nextValue()) != null) { JOptionPane.showMessageDialog( null, t, "Value from line " + shredder.getLastLineNumber(), JOptionPane.INFORMATION_MESSAGE ); }