- csv reader
- array of class
- for (:)
因為工作上需要讀取csv檔案的需求 , java 本身有提供一些 method
首先要 import opencsv-3.8.jar 檔案(我當時是3.8版本的)
讀取檔案路徑:
m_csvFile=""; //file path
//Chose CSV File
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION){
File selectedFile = fileChooser.getSelectedFile();
m_csvFile = selectedFile.getPath();
}else{
// error handle...
}
return true;
接著呼叫 CSVReader 物件:
reader = new CSVReader(new FileReader(m_csvFile));
// Reading All Records at once into a List<String[]>
List<String[]> records= reader.readAll(); //讀取csv資料到list裡面
reader.close();
// records.size() 就是讀取到 csv 所有筆數
SpcData spcAry[] = new SpcData[records.size()]; //宣告 array of class
for ( string[] csvRecord : records ) 的用法: 從records 陣列中,從第一個值取到最後一個值
for (String[] csvRecord : records) {
spcAry[count] = new SpcData();
spcAry[count].sht_id = csvRecord [0];
spcAry[count].mes_id = csvRecord [1];
spcAry[count].data_id = csvRecord [2];
spcAry[count].data_group= csvRecord [3];
spcAry[count].data_attr = csvRecord [4];
spcAry[count].u_spec = csvRecord [5];
spcAry[count].l_spec = csvRecord [6];
spcAry[count].data_value= csvRecord [7];
count++;
}
SpcData 的 Class:
private class SpcData {
String sht_id;
String mes_id;
String data_id;
String data_group;
String data_attr;
String l_spec;
String u_spec;
String data_value;
}
CSV Reader 參考網頁: https://www.callicoder.com/java-read-write-csv-file-opencs