检查外部文件中是否有某个单词,如果没有,请添加Java

问题描述

我正在编写一个类,其中必须将单词添加到外部文件中,前提是文件中不存在这些单词。 这是该方法代码,我必须写出文件中的单词,但是当我运行它时,它进入了一个循环,并且只连续打印一个单词:

public static void toDataFile(String word,String filename)
    {   
        try {
            File file = new File(filename);   
            Scanner sc2 = new Scanner(file);      
    
            while (sc2.hasNextLine())          
            {
                String w = sc2.nextLine();
                
                if(!(word.equals(w)))
                {
                    FileWriter myWriter = new FileWriter(filename,true);
                    PrintWriter printWriter = new PrintWriter(myWriter);
                
                    printWriter.println(word);
                    printWriter.close();
                }
            } 
        }
        catch(IOException e) {
            e.printstacktrace();
        }
}

这是我用来测试的三个数据文件

文件1: 我的测试文件一个

文件2: 我的测试文件

文件3: 我的测试文件

,这是该方法的结果: 测试 ...

它应该具有: 测试 文件 三个

edit:我切换了变量w和word,现在输出仍然是循环,现在执行ptp“ test file test file ...”

解决方法

问题在于此行:

printWriter.println(word);

因为您总是打印相同的单词。尝试用您的变量“ w”替换它,它应该可以工作。