[英]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.