gpt4 book ai didi

java - 读取多列文本文件并将其拆分为数组

转载 作者:太空宇宙 更新时间:2023-11-04 11:20:13 26 4
gpt4 key购买 nike

对于一个项目,我正在处理一个相当大的动物数据集,其中包含多达 14 个数据参数。我能够使用以下命令读取它并将其显示为字符串:

public static void readIn(String file) throws IOException {

Scanner scanner = new Scanner(new File(file));
while (scanner.hasNext()) {
String[] columns = scanner.nextLine().split("/t");
String data = columns[columns.length-1];
System.out.println(data);
}
}

并显示如下内容:

04:00:01    0.11    0.04    -0.1    1047470 977.91  91.75
04:00:01 0.32 -0.03 -0.07 1047505 977.34 92.91
04:00:01 0.49 -0.03 -0.08 1047493 978.66 92.17

但我目前在尝试将每一列拆分为单独的数组以便我可以处理数据(例如计算平均值)时遇到麻烦。知道我该怎么做吗?任何帮助将不胜感激。

编辑:谢谢,我找到了一个有效的解决方案,并且还可以让我选择它专门读取的 channel 。我还决定将数据存储为类中的数组,这就是我现在所拥有的:

public static void readChannel(String file, int channel) throws IOException 
{
List<Double> dataArr = new ArrayList<>();
Scanner scanner = new Scanner(new File(file));
while (scanner.hasNext()) {
String[] columns = scanner.nextLine().split("\t");

for (int i = channel; i < columns.length; i+=(columns.length-channel)) {
dataArr.add(Double.parseDouble(columns[i]));
dataArr.toArray();
}
}
}

最佳答案

您可以将所有行存储在 ArrayList 中,然后为每列创建数组并在其中存储值。示例代码:

Scanner scanner = new Scanner(new File(file));
ArrayList<String> animalData = new ArrayList<String>();
while (scanner.hasNext()) {
String[] columns = scanner.nextLine().split("/t");
String data = columns[columns.length-1];
animalData.add(data);
System.out.println(data);
}

int size = animalData.size();
String[] arr1 = new String[size]; String[] arr2 = new String[size];
String[] arr3 = new String[size]; String[] arr4 = new String[size];
for(int i=0;i<size;i++)
{
String[] temp = animalData.get(i).split("\t");
arr1[i] = temp[0];
arr2[i] = temp[1];
arr3[i] = temp[2];
arr4[i] = temp[3];
}

关于java - 读取多列文本文件并将其拆分为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44999680/

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