gpt4 book ai didi

java - 用 Java 读取 csv 文件。用一个数组列表填充一个数组列表

转载 作者:行者123 更新时间:2023-12-04 05:19:36 24 4
gpt4 key购买 nike

我尝试读出一个 csv 文件。在我的代码中,我读出了 csv 文件中的行。因此,我使用 arraylist 将行中的每个项目添加到 arraylist。

读出一行后,我将数组列表存储在另一个数组列表中,然后去读出下一行,依此类推。

现在我有几个问题和一个问题。

1)当我将一个项目添加到一个数组列表时,它是否总是添加在列表的en(当我没有像在我的代码中那样给出添加项目的特定位置时)?这样,将保留 csv 文件的顺序。

2)我发现,当我清除 arraylist datatemp 以准备读取下一行时,也清除了 array list data 的内容。如何防止我的代码这样做?

3)有没有办法从我拥有的数组列表数据中制作一个普通数组?

4)我读出 csv 文件的方式正确还是有更好的方法?

public class CSVReader {    

public void ReadCSV (String csvfilepath) {

BufferedReader CSVFile = null;
String dataRow = null;
ArrayList<Float> datatemp = new ArrayList<Float>();
ArrayList<ArrayList<Float>> data = new ArrayList<ArrayList<Float>>();

try {
CSVFile = new BufferedReader(new FileReader(csvfilepath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}

try {
dataRow = CSVFile.readLine();
} catch (IOException e) {
e.printStackTrace();
}

while (dataRow != null){
String[] dataArray = dataRow.split(",");
for (String item:dataArray) {
datatemp.add(Float.valueOf(item));
}
try {
dataRow = CSVFile.readLine();
} catch (IOException e) {
e.printStackTrace();
}

data.add(datatemp);
datatemp.clear();
}

try {
CSVFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

最佳答案

1) With this then the order of the csv-file would be keeped.



是的

2) How can I prevent my code from doing so?



每次都需要创建一个新的 tempArrayList:
while (dataRow != null){
datatemp = new ArrayList<Float>();

3) Is there a way to make an normal array out of the arraylist data I have?



您可以创建一个数组列表:
ArrayList[] array = data.toArray(new  ArrayList[data.size()]);

然后你可以递归地创建一个二维数组,但我会坚持使用更容易处理的列表列表。

4) Is my way of reading out the csv-File correct or is there any better way?



使用图书馆, there are many of them ,已经过测试。正确解析 CSV 文件比乍一看要困难得多。

关于java - 用 Java 读取 csv 文件。用一个数组列表填充一个数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13804612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com