gpt4 book ai didi

java - 将 .txt 文件转换为字符串的二维数组列表

转载 作者:太空宇宙 更新时间:2023-11-04 12:11:24 25 4
gpt4 key购买 nike

所以我尝试将 .txt 文件转换为以下格式:

1 2 3 4 
5 6 7 8
9 1 0 1

到字符串的二维数组列表中。这也应该可以与任何其他东西复制,例如

EXTENDING RETRACTING RETRACTING EXTENDING
EXTENDING EXTENDING RETRACTING
RETRACTING

这是我的代码

public class Test {
public static ArrayList<ArrayList<String>> readFromFile(String path) throws FileNotFoundException{
@SuppressWarnings("resource")
Scanner in = new Scanner(new File(path));
ArrayList<ArrayList<String>> comments= new ArrayList<ArrayList<String>>();
ArrayList<String> words = new ArrayList<String>();
String[] line;
String str;
String [] values;
while(in.hasNextLine()){
str=in.nextLine();
line = str.split("\t");
values = line[2].split(" ");
for(String word : values){
words.add(word);
}
}
comments.add(words);
return comments;
}

public static void main(String[] args) throws FileNotFoundException{
ArrayList<ArrayList<String>> inputs = readFromFile("/Users/Jason/yaw.txt");
int k = 0;
for(int i = 0; i < inputs.size(); i++){
for(int j = 0; j < inputs.get(k).size(); j++){
System.out.print(inputs.get(i).get(j));
k++;
}
System.out.println();
}
}
}

目前,它返回此错误。

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Test.readFromFile(Test.java:19)
at Test.main(Test.java:31)

关于如何使其正常工作有任何帮助吗?

最佳答案

这是解决这个问题的一种方法:

    // read file into list
List<String> linesInFile = Files.readAllLines(Paths.get("filename.txt"));
// create 2d array based on number of lines
List<List<String>> array = new ArrayList<>(linesInFile.size());

// iterate through every line of the file and split the elements using whitespace
linesInFile.forEach(line -> {
// get the elements in the current line
String[] elements = line.split("\\s+");
// store it in our 2d array
array.add(Arrays.asList(elements));
});

// print every row in our 2d array
array.forEach(System.out::println);

Files.readAllLines方法将返回一个列表,其中包含文件中的所有行(与您自己的版本类似)。

编辑:转换List<List<String>>进入ArrayList<ArrayList<String>>就像下面这样:

    ArrayList<ArrayList<String>> arrayList = new ArrayList<>();
array.forEach(row -> arrayList.add(new ArrayList<>(row)));

System.out.println(arrayList.getClass());
System.out.println(arrayList.get(0).getClass());

将输出:

    >> class java.util.ArrayList
>> class java.util.ArrayList

关于java - 将 .txt 文件转换为字符串的二维数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39822284/

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