我正在编写此代码以从文本文件中删除单词,但似乎无法使扫描程序正常工作。它适用于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);
}
答案 0 :(得分:1)
while((currentLine = reader.next()) != null)
使用next()
代替hasNext()
。
hasNext()
- 这只会说明输入中是否还有其他令牌。
next()
- 这将从其输入中返回下一个完整的标记。
答案 1 :(得分:1)
应该是
Scanner reader = new Scanner(new File(inputFile));
FileWriter writer = new FileWriter(tempFile);
while(reader.hasNextLine()) {
String currentLine = reader.nextLine();
...