Java使用PrintWriter写文件及Scanner读取内容存数组异常求助
问题根因梳理
- 数组索引越界问题:Java数组下标从0开始,原始代码循环变量从1开始遍历,为了覆盖3个元素不得不把数组长度设为4,属于基础语法错误。
- Scanner读取失败问题:
new Scanner(String)构造方法是直接扫描传入的字符串本身,不是把字符串作为文件路径读取文件。你需要传入File对象才能读取指定路径的文件内容,这是输出[Uebung_8.txt]的直接原因。 - 文件内容不符合预期、拆分结果错误:写入的单元格内容包含内部空格(
Zelle+ 数字),按空白符拆分后1个单元格会被拆成Zelle和数字两个元素,同时每个单元格末尾多余空格会导致拆分出空字符串。 - 隐式越界风险:读取文件时没有限制读取行数,若文件行数超过
newArray的行数会直接抛出数组越界异常。
修正后代码
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class Uebung8 { public static void main(String[] args) { String fileName = "Uebung_8.txt"; // 需求是3行3列,直接设置为3即可 int cols = 3; int rows = 3; String[][] arr = new String[rows][cols]; // 写入文件逻辑,用try-with-resources自动关流 try (PrintWriter writer = new PrintWriter(fileName)) { // 数组下标从0开始遍历 for (int zeile = 0; zeile < rows; zeile++) { for (int spalte = 0; spalte < cols; spalte++) { // 单元格内部不要留空格,单元格之间用空格分隔 arr[zeile][spalte] = "Zelle" + (spalte + 1); writer.print(arr[zeile][spalte] + " "); } writer.println(); } } catch (FileNotFoundException e) { e.printStackTrace(); return; // 写入失败直接终止程序 } // 读取文件逻辑 String[][] newArray = new String[rows][cols]; int controlZeile = 0; try (Scanner fileScan = new Scanner(new File(fileName))) { // 加行数校验避免数组越界 while (fileScan.hasNextLine() && controlZeile < rows) { String zeile = fileScan.nextLine().trim(); // 去掉首尾多余空格 String[] splitRes = zeile.split("\\s"); // 复制元素避免拆分结果长度和列数不一致导致越界 System.arraycopy(splitRes, 0, newArray[controlZeile], 0, Math.min(splitRes.length, cols)); controlZeile++; } } catch (FileNotFoundException e) { e.printStackTrace(); return; } // 按预期格式输出 for (int i = 0; i < controlZeile; i++) { System.out.println(String.join("", newArray[i])); } } }
运行效果
- 生成的
Uebung_8.txt内容:
Zelle1 Zelle2 Zelle3 Zelle1 Zelle2 Zelle3 Zelle1 Zelle2 Zelle3
- 控制台输出:
Zelle1Zelle2Zelle3 Zelle1Zelle2Zelle3 Zelle1Zelle2Zelle3
如果需要保留Zelle和数字之间的空格,只需要把单元格内容改为"Zelle " + (spalte+1),同时将split的分隔符改为两个空格(\\s{2})即可,保证1个单元格拆分后对应1个元素。
内容的提问来源于stack exchange,提问作者Franz Biberkopf
相关产品推荐
相关产品推荐

