
在java应用程序中处理结构化数据时,从文本文件读取数据并将其组织成矩阵(二维数组)是一种常见的需求。本教程将指导您完成这一过程,假设您的文本文件每行包含一串数字,且行与行之间没有分隔符,例如:
123 456
我们将创建一个静态方法来封装这一逻辑,使其可重用。
在填充矩阵之前,我们需要知道它的行数和列数。这通常需要对文件进行一次预扫描。行数可以通过计算文件中的总行数来确定,而列数则可以通过读取第一行的长度来确定(假设所有行的长度相同)。
以下是确定矩阵维度的方法:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MatrixReader {
/**
* 从文本文件读取矩阵并填充。
* 假设文件格式为每行一串数字,无分隔符,且所有行长度相同。
*
* @param filePath 文本文件的路径
* @return 填充好的二维整数矩阵
* @throws FileNotFoundException 如果文件不存在
*/
public static int[][] readMatrixFromFile(String filePath) throws FileNotFoundException {
File file = new new File(filePath);
// 第一次扫描:确定矩阵维度
int rows = 0;
int cols = 0;
try (Scanner dimensionScanner = new Scanner(file)) {
if (dimensionScanner.hasNextLine()) {
String firstLine = dimensionScanner.nextLine();
cols = firstLine.length(); // 列数等于第一行的字符数
rows++; // 第一行已计入
}
while (dimensionScanner.hasNextLine()) {
dimensionScanner.nextLine();
rows++; // 统计剩余行数
}
} // dimensionScanner 会自动关闭
if (rows == 0 || cols == 0) {
throw new IllegalArgumentException("文件为空或格式不正确,无法确定矩阵维度。");
}
// 初始化矩阵
int[][] matrix = new int[rows][cols];
// 第二次扫描:填充矩阵
try (Scanner dataScanner = new Scanner(file)) {
int currentRow = 0;
while (dataScanner.hasNextLine()) {
String line = dataScanner.nextLine();
// 确保行长度与预期的列数匹配
if (line.length() != cols) {
throw new IllegalArgumentException("文件格式不一致:行长度不匹配。");
}
char[] charArray = line.toCharArray(); // 将行转换为字符数组
for (int currentCol = 0; currentCol < cols; currentCol++) {
// 将字符转换为数字值
// 注意:Character.getNumericValue() 适用于单个数字字符 '0'-'9'
matrix[currentRow][currentCol] = Character.getNumericValue(charArray[currentCol]);
}
currentRow++;
}
} // dataScanner 会自动关闭
return matrix;
}
public static void main(String[] args) {
// 示例用法:假设您的文件名为 'url.txt' 位于项目根目录的 'src/User/' 下
String filePath = "./src/User/url.txt";
try {
int[][] myMatrix = readMatrixFromFile(filePath);
// 打印矩阵以验证
System.out.println("成功从文件读取并填充矩阵:");
for (int i = 0; i < myMatrix.length; i++) {
for (int j = 0; j < myMatrix[0].length; j++) {
System.out.print(myMatrix[i][j] + " ");
}
System.out.println();
}
} catch (FileNotFoundException e) {
System.err.println("错误:文件未找到 - " + e.getMessage());
} catch (IllegalArgumentException e) {
System.err.println("错误:文件内容或格式问题 - " + e.getMessage());
} catch (Exception e) {
System.err.println("发生未知错误:" + e.getMessage());
e.printStackTrace();
}
}
}在确定了矩阵的维度并创建了相应大小的二维数组后,我们需要重新读取文件(或者确保Scanner回到文件开头),然后逐行填充矩阵。
立即学习“Java免费学习笔记(深入)”;
上述代码示例中的 readMatrixFromFile 方法已经包含了这两个步骤:第一次扫描用于确定维度,第二次扫描用于实际填充数据。
通过本教程,您应该能够掌握在Java中从特定格式的文本文件读取数据并填充到二维整数矩阵的方法。关键步骤包括预扫描文件以确定矩阵维度,然后进行第二次扫描以逐行解析字符并将其转换为数值。请务必注意文件格式的假设以及 Character.getNumericValue() 方法的适用性,并实施健壮的错误处理机制。
以上就是Java中从文本文件读取并填充矩阵的教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号