You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Eclipse中Java程序无法将指定单词写入新文件的问题排查

问题分析与修复方案

核心问题

你代码里的Scanner初始化犯了关键错误:直接传入字符串"words.txt"时,Scanner会把这个字符串本身当作输入内容,而不是去读取磁盘上名为words.txt的文件。这就导致循环里根本没读到任何文件内容,自然five.txt里什么都没有。

修复后的代码

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class WordFilter {
    public static void main(String[] args) {
        try (Scanner in = new Scanner(new File("words.txt"));
             PrintWriter out = new PrintWriter("five.txt")) {
            
            while (in.hasNext()) {
                String word = in.next();
                if (word.length() == 5) {
                    out.println(word);
                }
            }
        } catch (IOException e) {
            System.out.println("文件读写出错: " + e.getMessage());
        }
    }
}

关键修改说明

  • 将new Scanner("words.txt")改为new Scanner(new File("words.txt")),让Scanner真正读取指定文件。
  • 移除了main方法上的throws IOException,因为已经用try-catch处理了异常,没必要再声明抛出。
  • 调整了变量声明的位置,让代码更简洁规范。

额外注意事项

  • 确保words.txt文件位于项目的根目录下(和编译后的class文件同目录),如果文件在其他路径,需要传入完整的绝对路径,比如new File("D:/project/words.txt")。
  • 检查words.txt里的内容格式,Scanner.next()默认按空格分割单词,如果你的文件里单词是按换行分隔,也可以用in.hasNextLine()和in.nextLine()来读取。

内容的提问来源于stack exchange,提问作者Donat M.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 05:31:00