首先到該http://ostermiller.org/utils/download.html 地址下載com.Ostermiller.util cvs的jar包。有分別適合jdk 1.4 和jdk 1.5的兩個jar包。
我用的系適合jdk 1.4的Ostermiller Utils version 1.05.00 for Java 1.4 的jar包。
public class CsvFileParser{
private LabeledCSVParser csvParser;//csv解析器,對於第一行的表頭資訊,自動載入為索引關鍵字
private int currLineNum = -1;//檔案所讀到行數
private String[] currLine = null;//用來存放當前行的資料
/**//*
* 建構函式,
* Param: in InputStream 要解析的資訊流
* throws IOException
*/
protected CsvFileParser(InputStream in) throws IOException {
csvParser = new LabeledCSVParser(new ExcelCSVParser(in));
currLineNum = csvParser.getLastLineNumber();
/**//*
* 檢查是否還有資料
*
* return ture 還有一行資料,false 沒有資料
*/
public boolean hasMore() throws IOException {
currLine = csvParser.getLine();
currLineNum = csvParser.getLastLineNumber();
if (null == currLine)
return false;
return true;
}
/**//*
* 返回當前行資料,關鍵字所指向的資料
* param:String filedName 該行的表頭
* return:String 返回當前行資料,關鍵字所指向的資料
*/
public String getByFieldName(String fieldName) {
return csvParser.getValueByLabel(fieldName);
}
/**//*
* 關閉解析器
*
*
*/
public void close() throws IOException {
csvParser.close();
}
/**//*
* 讀取當前行資料
*
* return String[] 讀取當前行資料
*/
public String[] readLine() throws IOException {
currLine = csvParser.getLine();
currLineNum = csvParser.getLastLineNumber();
return currLine;
}
public getCurrLineNum(){
return currLineNum;
}
public static void main(String[] args) throws Exception {
//建立解析資訊流
InputStream in=new FileInputStream(new File("C:PerfLogsdata_000002.csv"));
//執行個體解析器CsvFileParser
CsvFileParser parser=new CsvFileParser(in);
//讀取資料
while(parser.hasMore()){
System.out.print(parser.getByFieldName("time")+" ");//time 系表頭資料
System.out.print(parser.getByFieldName("total")+" ");
System.out.print(parser.getByFieldName("dpc time")+" ");
System.out.print(parser.getByFieldName("Interrupt Time")+" ");
System.out.print(parser.getByFieldName("Processor Time")+"");
}
parser.close();
}
}