[英]Read numbers from txt.file and generate 2d array
例如我们有 file("Test2") 其中包含:
1 2 3 4 5
1 2 3 4 0
1 2 3 0 0
1 2 0 0 0
1 0 0 0 0
1 2 0 0 0
1 2 3 0 0
1 2 3 4 0
1 2 3 4 5
我们想从文件中读取它。 在这个例子中,行数和列数是已知的!!!
public class Read2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new FileReader("Test2"));
int[][] array = new int[9][5];
while (s.hasNextInt()) {
for (int i = 0; i < array.length; i++) {
String[] numbers = s.nextLine().split(" ");
for (int j = 0; j < array[i].length; j++) {
array[i][j] = Integer.parseInt(numbers[j]);
}
}
}
for (int[] x : array) {
System.out.println(Arrays.toString(x));
}
// It is a normal int[][] and i can use their data for calculations.
System.out.println(array[0][3] + array[7][2]);
}
}
// Output
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 0]
[1, 2, 3, 0, 0]
[1, 2, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 3, 0, 0]
[1, 2, 3, 4, 0]
[1, 2, 3, 4, 5]
7//result from sum
我的问题是:如果我有一个包含 x=rows 和 y=columns(未知大小)的文件,并且我想从文件中读取数字并将它们放入 2d 数组,就像前面的示例一样。 我应该写什么类型的代码?
处理完 stream 后,对资源使用 try 将关闭文件。
Files.lines
返回 stream。int[][]
数组中的 int 和 package 即可。null
。public static int[][] readInts(String fileName) {
try (Stream<String> lines = Files.lines(Path.of(fileName))) {
return lines.map(line->Arrays.stream(line.split("\\s+"))
.mapToInt(Integer::valueOf)
.toArray())
.toArray(int[][]::new);
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
注意:以上假设数组的每一行都在文件中的单独行上。 包含不同整数计数的行也可以工作。
这是使用 stream API 的解决方案:
var arr = new BufferedReader(new FileReader("PATH/TO/FILE")).lines()
.map(s -> s.split("\\s+"))
.map(s -> Stream.of(s)
.map(Integer::parseInt)
.toArray(Integer[]::new))
.toArray(Integer[][]::new);
正如@Andy Turner 所说,使用List<List<Integer>>
,因为List
在初始化时不会强制要求它的长度。 代码是这样的:
public class Read2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new FileReader("Test2"));
List<List<Integer>> list = new ArrayList<>();
// scan digits in every line
while (s.hasNextLine()) {
String str = s.nextLine();
String[] strSplitArr = str.split(" ");
list.add(Arrays.stream(strSplitArr)
.map(Integer::parseInt)
.collect(Collectors.toList()));
}
for (List<Integer> integersInOneLine : list) {
System.out.println(integersInOneLine.stream()
.map(Object::toString)
.collect(Collectors.joining(", ", "[", "]")));
System.out.println();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.