-3

我正在编写此代码以从文本文件中删除一个单词,但似乎无法让扫描仪工作。它可以使用,bufferedreader但我不允许使用它。我在这里做错了什么?

    public static void Option2Method(String dictionary) throws IOException 
{

    File inputFile = new File(dictionary);
    File tempFile = new File("TempDict.txt");
    String tempword = JOptionPane.showInputDialog(null, "Enter a word to remove");
    String lineToRemove = tempword.toLowerCase();
    lineToRemove = lineToRemove.replaceAll(",", "");
    lineToRemove = lineToRemove.replaceAll("\\.", "");
    lineToRemove = lineToRemove.replaceAll("\\?", "");
    lineToRemove = lineToRemove.replaceAll(" ", "");

    Scanner reader = new Scanner(new File(inputFile));
    FileWriter writer = new FileWriter(tempFile);
    String currentLine;

    while((currentLine = reader.hasNext()) != null)
    {
        String trimmedLine = currentLine.trim();
        if(trimmedLine.equals(lineToRemove)) continue;
        writer.write(currentLine + "\n");
    }
    reader.close();
    writer.close();
    inputFile.delete();
    tempFile.renameTo(inputFile);
}
4

2 回答 2

1
while((currentLine = reader.next()) != null)

使用next()而不是hasNext().

hasNext()- 这只会说明其输入中是否存在更多令牌。

next()- 这将从其输入返回下一个完整的令牌。

于 2013-04-09T09:42:51.480 回答
1

它应该是

Scanner reader = new Scanner(new File(inputFile));
FileWriter writer = new FileWriter(tempFile);
while(reader.hasNextLine()) {
   String currentLine = reader.nextLine();
   ...
于 2013-04-09T09:55:28.760 回答