我是java初学者,我不知道如何从CSV文件读取到2个ArrayLists,可能使用 token 和。类型。 (列表->数组) 根据我们添加到一个列表或另一个列表的 token 。
更新:文件的格式已修复。这是格式:
安德鲁,尼克,11,笔,苹果,背包,5500.0,570.0,4700.0
Ex:
Name,Description,55.0,100.0
Name into an ArrayList of String.
55.0 into an ArrayList of Double;
这是我的代码,我试图首先弄清楚基本的内容。
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();
}
}
最佳答案
您可以尝试以下代码。作为示例,我将索引零作为名称字段,将索引六作为您需要的 double 值。根据格式您可以获得实际的字段索引并将其添加到您的列表中。
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();
}
关于java - 如何根据文件中的数据类型将 CSV 文件读入 2 个 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55459964/