如何用Java读取未知行列数的文本文件并生成int二维数组?
动态读取未知行列数的文本文件生成int[][]二维数组
示例文件内容
现有文本文件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
已知行列数时的实现代码
当已知文件的行数和列数时,可通过以下Java代码读取文件内容并生成int[][]二维数组,同时可对数组数据进行计算:
import java.io.FileReader; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.Arrays; 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)); } // 可以使用数组数据进行计算 System.out.println(array[0][3] + array[7][2]); } }
输出结果
[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//求和结果
技术问询
若文本文件的行数x和列数y均未知,如何编写Java代码读取其中的数字并生成上述格式的int[][]二维数组?
解决方案
由于Java二维数组长度固定,无法直接动态扩展,可通过动态集合类临时存储数据,读取完成后再转换为目标格式数组,具体步骤:
- 使用
Scanner逐行读取文件内容; - 对每行内容按空白字符分割,转换为
int数组后存入List<int[]>; - 读取完成后,将
List转换为固定长度的int[][]数组。
实现代码
import java.io.FileReader; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.List; import java.util.ArrayList; import java.util.Arrays; public class ReadDynamicArray { public static void main(String[] args) throws FileNotFoundException { Scanner s = new Scanner(new FileReader("Test2")); List<int[]> tempList = new ArrayList<>(); // 逐行读取并转换为int数组,存入List while (s.hasNextLine()) { String line = s.nextLine().trim(); // 跳过空行(如果文件中有) if (line.isEmpty()) { continue; } String[] numberStrs = line.split("\\s+"); // 匹配任意空白字符(多个空格、制表符等) int[] row = new int[numberStrs.length]; for (int j = 0; j < numberStrs.length; j++) { row[j] = Integer.parseInt(numberStrs[j]); } tempList.add(row); } s.close(); // 将List转换为int[][]数组 int[][] array = tempList.toArray(new int[tempList.size()][]); // 输出验证 for (int[] x : array) { System.out.println(Arrays.toString(x)); } // 计算示例:取第一行第四列和第八行第三列求和 System.out.println(array[0][3] + array[7][2]); } }
代码说明
- 用
List<int[]>动态存储每行数据,规避提前知晓行列数的限制; - 使用
split("\\s+")替代split(" "),兼容一行内多个连续空格的情况; - 添加空行判断,避免空行导致的解析错误;
- 通过
toArray()方法将动态集合转换为固定长度的int[][]数组,完全符合需求格式。
输出结果
与已知行列数的代码输出完全一致:
[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
内容的提问来源于stack exchange,提问作者Nazary Petryshyn
相关产品推荐
相关产品推荐

