使用 Apache Commons CSV 处理 Java CSV 文件

Java 代码:[code]import java.io.*;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVStrategy;

public class CSVParseDemo {
public static void main(String[] args) throws IOException {
if (args.length < 1) {
System.out.println(“Usage: java CSVParseDemo <csv_file>”);
return;
}

CSVParser parser = new CSVParser(new FileReader(args[0]), CSVStrategy.EXCEL_STRATEGY);
String[] values = parser.getLine();
while (values != null) {
    printValues(parser.getLineNumber(), values);
    values = parser.getLine();
}
}

private static void printValues(int lineNumber, String[] as) {
System.out.println("Line " + lineNumber + " has " + as.length + " values:");
for (String s: as) {
    System.out.println("\t|" + s + "|");
}
System.out.println();
}

}[/code]测试输入文件:Test with a simple CSV file: 程序输出:[code]Line 1 has 11 values:
|psmith01|
|CLASS2B|
|Peter Smith 1|
|YEAR2|
|1|
|N|
|ADVANCED|
|STAFF|
|1|
|Y|
|Y|

Line 2 has 11 values:
|smehta|
|CLASS3G|
|Smeeta Mehta|
|LOCAL|
|1|
|Y|
|STANDARD|
|PUPIL|
|2.1|
|N|
|Y|[/code]