gpt4 book ai didi

java - 将 CSV 文件导出到数组中

转载 作者:行者123 更新时间:2023-12-01 13:19:10 26 4
gpt4 key购买 nike

我有一个包含不同数据列的 CSV 文件。

示例:

100, 0.1, 0.5
200, 0.1, 0.1
300, 0.2, 0.5

等等

我想将第一列存储到一个数组中,将第二列存储到自己的数组中,依此类推,以便我可以将它们用于数学方程。

import.java.util.Scanner; 
import java.io.File;

public class Example
{
public static void main(String[] args) throws Exception
{
Scanner s = new Scanner(new File("C://java//data.txt"));
}
}

到目前为止我还很迷茫。

最佳答案

You can try this:

public class ReadCSV {
public static List<List<Double>> getDimensionList(String key) throws Exception
{
List<List<Double>> listOfDimension = new ArrayList<List<Double>>();
List<Double> dimensionList = null;
File file = null;
BufferedReader br = null;
try {
file = new File(key);
br = new BufferedReader(new FileReader(file));

String strLine = "";
StringTokenizer dimensionVal = null;
int lineNumber = 0, tokenNumber = 0;
while( (strLine = br.readLine()) != null)
{
dimensionVal = new StringTokenizer(strLine, ",");
dimensionList = new ArrayList<Double>();
while(dimensionVal.hasMoreTokens())
{
tokenNumber++;
dimensionList.add(Double.parseDouble(dimensionVal.nextToken()));

if(tokenNumber == 3)
{
Comparator<Double> comparator = Collections.reverseOrder();
Collections.sort(dimensionList,comparator);

}
}
listOfDimension.add(dimensionList);
tokenNumber = 0;
lineNumber++;
}
}catch (Exception e) {
throw new Exception();
}
finally
{
if(br != null)
br.close();
}
return listOfDimension;
}

public static void main(String[] args) throws Exception {
System.out.println(getDimensionList("dimension_details.csv"));
}

关于java - 将 CSV 文件导出到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22186309/

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