Java读取多份matrix.txt文件并存储行列数的实现求助
解决方案
核心思路
- 遍历命令行传入的所有矩阵文件路径
- 对每个文件,先读取第一行的两个整数,分别作为矩阵的行数和列数(可根据实际文件格式调整顺序)
- 逐行读取后续内容,将每行数值解析为整数,存储到二维数组中
- 用自定义类封装每个矩阵的行数、列数和内容,统一管理数据
完整代码实现
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; // 封装单个矩阵的元数据和内容 class MatrixInfo { private int rows; private int cols; private int[][] matrix; public MatrixInfo(int rows, int cols, int[][] matrix) { this.rows = rows; this.cols = cols; this.matrix = matrix; } // Getter方法,方便后续获取数据 public int getRows() { return rows; } public int getCols() { return cols; } public int[][] getMatrix() { return matrix; } } public class MatrixReader { public static void main(String[] args) { List<MatrixInfo> matrixList = new ArrayList<>(); if (args.length == 0) { System.out.println("请传入至少一个矩阵文件路径"); System.exit(1); } // 遍历所有传入的文件 for (String filePath : args) { File file = new File(filePath); try (Scanner sc = new Scanner(file)) { // 读取第一行的行数和列数,若文件格式是列数在前,交换两者顺序即可 int rows = sc.nextInt(); int cols = sc.nextInt(); sc.nextLine(); // 跳过第一行剩余的换行符 // 初始化二维数组存储矩阵内容 int[][] matrix = new int[rows][cols]; // 逐行读取并解析矩阵数据 for (int i = 0; i < rows; i++) { // 按任意数量空格分割每行内容,兼容多空格分隔场景 String[] numStrs = sc.nextLine().trim().split("\\s+"); for (int j = 0; j < cols; j++) { matrix[i][j] = Integer.parseInt(numStrs[j]); } } matrixList.add(new MatrixInfo(rows, cols, matrix)); System.out.printf("成功读取文件 %s:行数=%d,列数=%d%n", filePath, rows, cols); } catch (IOException e) { System.err.printf("读取文件 %s 失败:%s%n", filePath, e.getMessage()); System.exit(1); } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { System.err.printf("文件 %s 格式错误:%s%n", filePath, e.getMessage()); System.exit(1); } } // 测试输出(可选):打印第一个矩阵的内容 if (!matrixList.isEmpty()) { MatrixInfo firstMatrix = matrixList.get(0); System.out.println("\n第一个矩阵内容:"); for (int[] row : firstMatrix.getMatrix()) { for (int num : row) { System.out.print(num + " "); } System.out.println(); } } } }
关键细节说明
- 文件格式适配:如果你的矩阵文件第一行是列数在前、行数在后(比如示例文件第一行
4 6实际对应6列、8行),只需把int rows = sc.nextInt(); int cols = sc.nextInt();改成int cols = sc.nextInt(); int rows = sc.nextInt(); - 多文件处理:支持同时传入多个文件路径,一次性读取所有矩阵
- 异常处理:覆盖了文件IO错误、格式错误等场景,给出明确的错误提示
- 数据存储:用
List<MatrixInfo>统一管理所有矩阵,后续可直接通过Getter方法获取行数、列数和矩阵内容
使用方式
编译后,将三个矩阵文件路径作为命令行参数传入:
java MatrixReader matrix1.txt matrix2.txt matrix3.txt
内容的提问来源于stack exchange,提问作者turtlered9
相关产品推荐
相关产品推荐

