可能重复:
Java - 在文件中查找一行并删除
我正在尝试从文本文件中删除一整行,并且如果只有一行没有空格的完整文本行,我已经设法删除了该行。如果我在字符串之间有空格分隔符,则无法删除任何内容。代码如下:
import java.io.*;
import java.util.Scanner;
public class removebooks {
// construct temporary file
public static void main(String[]args)throws IOException {
String title;
Scanner titlerem= new Scanner (System.in);
System.out.println("Enter Title to remove from file");
title = titlerem.next ();
// construct temporary file
File inputFile = new File("books.txt");
File tempFile = new File(inputFile + "temp.txt");
BufferedReader br = new BufferedReader (new FileReader("books.txt"));
PrintWriter Pwr = new PrintWriter(new FileWriter (tempFile));
String line = null;
//read from original, write to temporary and trim space, while title not found
while((line = br.readLine()) !=null) {
if(line.trim().equals(title)){
continue; }
else{
Pwr.println(line);
Pwr.flush();
}
}
// close readers and writers
br.close();
Pwr.close();
titlerem.close();
// delete book file before renaming temp
inputFile.delete();
// rename temp file back to books.txt
if(tempFile.renameTo(inputFile)){
System.out.println("Update succesful");
}else{
System.out.println("Update failed");
}
}
}
文本文件名为 books.txt,其内容应如下所示:
bookone author1 subject1
booktwo author2 subject2
bookthree author3 subject3
bookfour author4 subject4
谢谢您的任何帮助将不胜感激