
在java编程中,从外部文件读取数据并将其组织成特定的数据结构是常见的任务。本教程将指导您如何从一个每行包含一串数字字符的文本文件(例如,123 456)中读取数据,并将其填充到一个二维整型矩阵(int[][])中。
在填充矩阵之前,我们需要知道矩阵的行数(m)和列数(n)。这通常需要对文件进行一次预扫描。行数可以通过计算文件中的行数来确定,而列数则可以通过读取第一行的长度来确定。
以下代码片段展示了如何实现这一预扫描过程:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MatrixReader {
/**
* 预扫描文件以确定矩阵的行数和列数。
* 假定文件格式为每行一串数字字符,且每行长度相同。
*
* @param filePath 文本文件的路径。
* @return 包含行数和列数的整数数组,如 {rows, cols}。
* @throws FileNotFoundException 如果文件不存在。
*/
public static int[] getMatrixDimensions(String filePath) throws FileNotFoundException {
int rows = 0;
int cols = 0;
File file = new File(filePath);
Scanner scanner = null; // 声明在try块外部,以便finally块可以访问
try {
scanner = new Scanner(file);
if (scanner.hasNextLine()) {
String firstLine = scanner.nextLine();
cols = firstLine.length(); // 列数等于第一行字符的长度
rows++; // 第一行已计入
}
while (scanner.hasNextLine()) {
scanner.nextLine();
rows++; // 统计剩余行数
}
} finally {
if (scanner != null) {
scanner.close(); // 确保Scanner资源被关闭
}
}
return new int[]{rows, cols};
}
}注意事项:
获取到矩阵的维度后,我们可以再次遍历文件,将数据逐行逐字符地填充到预先创建的二维矩阵中。
立即学习“Java免费学习笔记(深入)”;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class MatrixReader {
// ... (getMatrixDimensions 方法如上) ...
/**
* 从指定文本文件读取数据并填充到二维整型矩阵中。
* 假定文件格式为每行一串数字字符,且每行长度相同。
*
* @param filePath 文本文件的路径。
* @return 填充好的二维整型矩阵。
* @throws FileNotFoundException 如果文件不存在。
*/
public static int[][] readMatrixFromFile(String filePath) throws FileNotFoundException {
// 1. 获取矩阵维度
int[] dimensions = getMatrixDimensions(filePath);
int rows = dimensions[0];
int cols = dimensions[1];
// 2. 创建矩阵
int[][] matrix = new int[rows][cols];
// 3. 再次打开文件并填充矩阵
File file = new File(filePath);
Scanner scanner = null; // 声明在try块外部
try {
scanner = new Scanner(file);
int currentRow = 0; // 当前正在填充的行索引
while (scanner.hasNextLine() && currentRow < rows) {
String line = scanner.nextLine(); // 读取一行数据
char[] charArray = line.toCharArray(); // 将行转换为字符数组
// 遍历字符数组,将每个字符转换为数字并填充到矩阵中
for (int currentCol = 0; currentCol < cols; currentCol++) {
// 使用 Character.getNumericValue 将字符转换为对应的整数值
matrix[currentRow][currentCol] = Character.getNumericValue(charArray[currentCol]);
}
currentRow++; // 移动到下一行
}
} finally {
if (scanner != null) {
scanner.close(); // 确保Scanner资源被关闭
}
}
return matrix;
}
/**
* 主方法,用于演示如何使用 readMatrixFromFile。
*/
public static void main(String[] args) {
// 假设您的文件名为 'url.txt',位于项目根目录下的 'src/User/' 文件夹
// 请根据您的实际文件路径进行调整
String filePath = "./src/User/url.txt";
// 创建一个示例文件用于测试 (如果文件不存在,请手动创建或在此处添加文件写入逻辑)
// 例如,创建一个名为 'url.txt' 的文件,内容如下:
// 123
// 456
// 789
try {
int[][] resultMatrix = readMatrixFromFile(filePath);
// 打印矩阵以验证结果
System.out.println("成功从文件读取并填充矩阵:");
for (int i = 0; i < resultMatrix.length; i++) {
System.out.println(Arrays.toString(resultMatrix[i]));
}
} catch (FileNotFoundException e) {
System.err.println("错误:文件未找到 - " + filePath);
// e.printStackTrace(); // 打印完整的堆栈跟踪,便于调试
} catch (Exception e) {
System.err.println("发生未知错误:" + e.getMessage());
// e.printStackTrace();
}
}
}Character.getNumericValue(char) 的局限性:
异常处理:
资源管理:
文件路径:
通过上述步骤,您可以高效地从特定格式的文本文件读取数据并将其填充到Java的二维整型矩阵中。关键在于分两步走:首先确定矩阵维度,然后进行数据填充。同时,理解 Character.getNumericValue 的工作原理及其局限性,并根据实际文件格式选择合适的解析方法,是确保数据正确性的重要环节。良好的异常处理和资源管理习惯也将使您的代码更加健壮和可靠。
以上就是Java:从文本文件读取数据并填充二维矩阵的实现指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号