可能重复:
Java - Find a line in a file and remove的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
感谢你的帮助,将不胜感激
使用搜索功能可以节省大量时间。 – Woot4Moo