我已经读取了一个整数.txt文件,该文件具有不同长度的行到一个数组中。我现在需要将这些行细分为单个数组或2d数组。 .txt文件的行长可以更改,但是行数不会更改。考虑到行长可能会因文件而异,我愿意就如何将文件读入锯齿状数组提出建议。
。txt文件如下所示:
4 6 4 2 1 6 1 6 1 6 1
7 0 1 2 0 3 0 4 2 3 0 3 2 0 1 2 0 1 7 0 1
1 2 3 4 1 2 5 1 2 3 4 5
1 2 1 3 1 8 1 1 2 5 4 3 4 7 0 7 1 0 1 2 1 2 7 1 2
5 1 3 1 4 5 1 3 5 2 2 3 4 5 4 2 1 4 1 2 3
这是我的代码:
1 import java.io.BufferedReader;
2 import java.io.FileReader;
3 import java.io.IOException;
4
5
6 public class FileIn{
7
8
9 public static int [] [] PageList = new int [5] [];
10
11 public static int [] Pages;
12
13
14 public static void FileImport() throws IOException {
15
16
17 BufferedReader p = new BufferedReader(new FileReader("reference_strings_0010.txt"));
18
19 String Line;
20
21 while ((Line = p.readLine()) != null) {
22
23 Lines.add(Line);
24 String [] IntLine = Line.split(" ");
25 int [] temp = new int [IntLine.length];
26
27 for (int i = 0; i < temp.length; i++) {
28
29 temp [i] = Integer.parseInt(IntLine[i]);
30 Pages = new int [temp.length];
31 Pages = temp;
32 }
33
34 }
35
36 p.close();
37
38 }
当前,.txt文件以这种格式读入数组:
[4 6 4 2 1 6 1 6 1 6 1, 7 0 1 2 0 3 0 4 2 3 0 3 2 0 1 2 0 1 7 0 1, 1 2 3 4 1 2 5 1 2 3 4 5, 1 2 1 3 1 8 1 1 2 5 4 3 4 7 0 7 1 0 1 2 1 2 7 1 2, 5 1 3 1 4 5 1 3 5 2 2 3 4 5 4 2 1 4 1 2 3]
我希望每个整数都是其自己的元素的数组,并且每个数组应在逗号分隔的位置分开。
任何帮助,我们将不胜感激。
如果最终答案的长度会有所不同,则应考虑使用ArrayList
。另外,您应该将解析包装在try-catch块中,以处理格式错误的输入。您可以像这样将值存储在2D ArrayList中:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileIn{
public static int [] [] PageList = new int [5] [];
public static int [] Pages;
public static void FileImport() throws IOException {
BufferedReader p = new BufferedReader(new FileReader("reference_strings_0010.txt"));
String Line;
ArrayList<ArrayList<Integer>> arr = new ArrayList<>();
while ((Line = p.readLine()) != null) {
Lines.add(Line);
String [] IntLine = Line.split(" ");
ArrayList<Integer> innerList = new ArrayList<>();
for (int i = 0; i < IntLine.length; i++) {
try {
int temp = Integer.parseInt(IntLine[i]);
innerList.add(temp);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
arr.add(innerList);
}
p.close();
}
此处,arr
将包含以下格式的最终值:
[ [4, 6, 4, 2, 1, 6, 1, 6, 1, 6, 1],
[7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 0, 1, 2, 0, 1, 7, 0, 1],
[1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5],
[1, 2, 1, 3, 1, 8, 1, 1, 2, 5, 4, 3, 4, 7, 0, 7, 1, 0, 1, 2, 1, 2, 7, 1, 2],
[5, 1, 3, 1, 4, 5, 1, 3, 5, 2, 2, 3, 4, 5, 4, 2, 1, 4, 1, 2, 3] ]