如何使用BufferedReader将两行整数文本转换为二维数组?
使用BufferedReader将文本转换为二维数组的实现方案
以下是基于Java的实现步骤和代码,针对你给出的文本格式(包含空行,每行以空格分隔整数):
核心处理步骤
- 用
BufferedReader逐行读取文本内容 - 跳过空行(判断行内容去除首尾空格后是否为空)
- 将有效行按任意数量空格拆分为字符串数组,再转换为整数数组
- 收集所有整数数组,最终转换为二维
int数组
代码实现
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class TextTo2DArray { public static void main(String[] args) { String filePath = "你的文本文件路径"; // 替换为实际文件路径 List<int[]> rows = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { String line; while ((line = br.readLine()) != null) { // 跳过空行 String trimmedLine = line.trim(); if (trimmedLine.isEmpty()) { continue; } // 按单个或多个空格拆分字符串 String[] numStrs = trimmedLine.split("\\s+"); int[] row = new int[numStrs.length]; // 转换为整数数组 for (int i = 0; i < numStrs.length; i++) { row[i] = Integer.parseInt(numStrs[i]); } rows.add(row); } // 转换为二维数组 int[][] result = rows.toArray(new int[rows.size()][]); // 验证输出 for (int[] row : result) { for (int num : row) { System.out.print(num + " "); } System.out.println(); } } catch (IOException e) { e.printStackTrace(); } catch (NumberFormatException e) { System.err.println("文本中包含非整数内容"); e.printStackTrace(); } } }
关键细节说明
- 使用
try-with-resources语法自动关闭BufferedReader,避免资源泄漏 - 用
trim()和isEmpty()精准判断空行,过滤文本中的无效空白行 - 拆分字符串时用
\\s+正则表达式,兼容单个或多个连续空格的分隔场景 - 捕获
NumberFormatException,处理文本中存在非数字内容的异常情况
内容的提问来源于stack exchange,提问作者Minh Anh
相关产品推荐
相关产品推荐

