将文本文件转换为多个数组

问题描述 投票:0回答:1

我试图将具有多个字符串的文本文件转换为多个数组,但代码将它们打印在一个数组中。代码如下

File file = new File("C://Users//DELL//Desktop//PSOFS+10CV//AA.txt");
Scanner scan = new Scanner(file);
List<String> lines = new ArrayList<String>() ;
while(scan.hasNextLine()){
    lines.add(scan.nextLine());
}

String[] array = lines.toArray(new String[0]);
System.out.println(Arrays.toString(array));

我的文本文件是这样的

[1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0][1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0][0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0][1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1][0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0] [1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0] 

上面的代码给出了以下结果

[[1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0] , [1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0] , [1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1], [0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0], [1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0] ]

所有字符串都打印在一个数组中,而我需要多个数组而不是一个数组。谢谢大家

java arrays
1个回答
0
投票

如果您的文本全部在一行中(如示例文本所示),则nextLine()将该行放入一个String中。您必须在将文本读入所需的部分后将其拆分,例如

String line=scan.nextLine();
Matcher matcher=new Pattern("(\\[[^\\]]+\\])").matcher(line);
while(matcher.find())
 lines.add(matcher.group(0))
© www.soinside.com 2019 - 2024. All rights reserved.