如何在 Java 中删除或修剪文本文件中的一行?这是我的程序,但它不起作用。我想删除文本文件中的一行,一行包含用户输入的单词
try {
File inputFile = new File("temp.txt");
File tempFile = new File("temp1.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = name;
String currentLine;
while((currentLine = reader.readLine()) != null)
{
//trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(!trimmedLine.startsWith(lineToRemove))
{
// if current line not start with lineToRemove then write to file
writer.write(currentLine);
}
}
writer.close();
reader.close();
}
catch(IOException ex)
{
System.out.println("Error reading to file '" + fileName + "'");
}