我有一种方法可以从文本文件中以单词列表格式删除单词,但是它会不断删除文件中的所有数据,而不是特定单词
public static void Option2Method() throws IOException
{
File inputFile = new File("wordlist.txt");
File tempFile = new File("TempWordlist.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
String currentLine;
while((currentLine = reader.readLine()) != null)
{
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine);
}
boolean successful = tempFile.renameTo(inputFile);
}
最佳答案
该代码必须在编写器上调用close()
。
确保数据从缓冲区到达实际文件:
while((currentLine = reader.readLine()) != null)
{
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine);
}
writer.close();
reader.close();
考虑使用try / catch / finally块以确保即使抛出
IOException
时流也被关闭。关于java - 从文本文件中删除单词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15665970/