Java文件处理程序调用writer方法反复抛出NoSuchElementException如何解决
问题根因
你遇到的NoSuchElementException和文件写入逻辑无关,你之前在br.write段加的try-catch完全没有命中异常抛出点,异常实际是主方法里的Scanner.nextInt()触发的,核心原因如下:
- 你在
writer1、reader1等所有子功能方法中,都单独创建了绑定System.in的Scanner实例,并且在方法结束时主动调用了这些Scanner的close()方法。 Scanner关闭时会同步关闭它绑定的输入流,而System.in是JVM全局的标准输入流,一旦关闭就无法重新打开。- 当你执行完一次写入功能回到主菜单时,主方法里的
Scanner x尝试读取用户输入,此时System.in已经被提前关闭,没有可用的输入源,就会抛出NoSuchElementException。
修复方案
1. 统一使用全局唯一的Scanner实例
全程只创建一个绑定System.in的Scanner,在主方法调用子功能时将该实例作为参数传递,不要在子方法中单独创建Scanner,也不要在子方法中关闭Scanner,只在主程序选择退出时统一关闭即可。
修改示例:
// 主方法调用子功能时传参 public static void main(String[] args){ Scanner x = new Scanner(System.in); while(true){ System.out.println("1. write 2. read 3. delete 4. create 5.exit"); System.out.print("Enter choice: "); int ch = x.nextInt(); // 吃掉nextInt()遗留的换行符,避免后续nextLine()读空 x.nextLine(); if(ch==1){ writer1 var0 = new writer1(); var0.function1(x); } // 其余子功能调用同理传参 if(ch==5){ System.out.println("exited, thank you for using program"); x.close(); break; } } } // 子方法接收Scanner参数,删除内部所有Scanner创建、关闭逻辑 class writer1{ void function1(Scanner scanner){ System.out.print("Input file name: "); String path = scanner.nextLine(); File file = new File("D:\\"+path); System.out.print("input number of lines: "); int n = scanner.nextInt(); scanner.nextLine(); // 吃掉nextInt()遗留的换行符 System.out.print("input data: "); String data = scanner.nextLine(); // 其余文件处理逻辑不变,删除原有y/a/z三个Scanner的相关代码 } }
2. 修复写入逻辑的问题
你当前的写入逻辑存在错误:for循环中每次都新建FileWriter,默认是覆盖写入模式,最终执行完只会保留1行内容。需要把FileWriter和BufferedWriter的创建逻辑移到for循环外面,如果需要追加写入可以在创建FileWriter时指定第二个参数为true。
示例:
try { // 流对象创建移到循环外 fr = new FileWriter(file, true); br = new BufferedWriter(fr); for(int i = n; i>0;i--){ br.write(datawithnewline); } } catch (IOException e) { System.out.print("error"); }
内容的提问来源于stack exchange,提问作者Subramani Easwaran
相关产品推荐
相关产品推荐

