[英]How can I read from a CSV file into 2 ArrayLists depending on the data type I have got in the File?
我是Java的初學者,我不知道如何將CSV文件讀取到2個ArrayLists中,也許使用標記and。 類型。 (list-> Array)取決於我們添加到一個列表或另一個列表的令牌。
更新:文件格式是固定的。 格式如下:
安德魯,尼克,11,筆,蘋果,背包,5500.0,570.0,4700.0
例如:
名稱,說明,55.0、100.0
命名為String的ArrayList。
55.0放入Double的ArrayList中;
這是我的代碼,旨在首先弄清基本知識。
public class CSVRead {
public static void main(String[] arg) throws Exception {
BufferedReader CSVFile = new BufferedReader(new FileReader("Auto2.csv"));
String data= CSVFile.readLine();
while (data != null){
String[] dataArray = data.split(",");
for (String item:dataArray) {
System.out.print(item + "\t");
}
System.out.println();
data = CSVFile.readLine();
}
CSVFile.close();
System.out.println();
}
}
您可以嘗試以下代碼。 例如,我將索引零作為名稱字段並將索引六作為所需的雙精度值。 根據格式,您可以獲取實際的字段索引並將其添加到列表中。
public void loadData() throws IOException {
List<String> namesList = new ArrayList<>();
List<Double> someDoubleList = new ArrayList<>();
BufferedReader CSVFile = new BufferedReader(new FileReader("/Users/leon/Desktop/Auto2.csv"));
String data = CSVFile.readLine();
while (data != null) {
String[] dataArray = data.split(",");
// Add the names to string list as the index of it is zero
namesList.add(dataArray[0]);
// Add the double value to double list as the index of it is six.
someDoubleList.add(Double.parseDouble(dataArray[6]));
data = CSVFile.readLine();
}
CSVFile.close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.