Java从文件中删除完整行

时间:2013-01-10 20:17:58

标签: java

  

可能重复:
  Java - Find a line in a file and remove

我正在尝试从文本文件中删除一个完整的行,并且如果只有一个不间断的文本行没有空格,则设法删除该行。如果我在字符串之间有空格分隔符,则无法删除任何内容。 代码如下:

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

谢谢你的任何帮助将不胜感激

3 个答案:

答案 0 :(得分:3)

为什么不使用

if(line.trim().startsWith(title))

而不是

if(line.trim().equals(title))

因为equals()仅在两个字符串相等时才为真,如果line.trim()title开头,则startsWith()为真;)

答案 1 :(得分:1)

当您逐行阅读文件时。您可以使用以下

  if(line.contains(title)){
     // do something
  }

在这种情况下,您不会仅受标题限制。

String API

答案 2 :(得分:0)

br.readLine()将变量line的值设置为“bookone author1 subject1”。

Scanner.next()以空格分隔。您需要将对Scanner.next()的所有调用合并到单个String中,然后再检查文件中的行,如果这是您的意图。

在您的情况下,如果您输入“bookone author1 subject1”,则在致电title后,变量Scanner.next()的值将为“bookone”。

相关问题