2013-01-10 101 views
1

可能重复:
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 

感谢你的帮助,将不胜感激

+3

使用搜索功能可以节省大量时间。 – Woot4Moo

回答

3

你为什么不使用

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

,而不是

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

因为如果两个字符串相等equals()只有真实的,startsWith()为真,当line.trim()开始于title

+0

我没有搜索并找到示例代码Woot4Moo,但这是我已经实现的一行中的单个字符串。字符串之间的空间导致了我的问题。 –

0

br.readLine()设置变量line为“bookone作者1 subject1”的值。

Scanner.next()用空格分隔。您需要将所有对Scanner.next()的调用合并为一个字符串,然后检查文件中的行,如果这是您的意图。

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

+1

我想OP要删除整行,如果用户输入_bookone_ – jlordo

+0

我会认为这是正确的,因为该变量被命名为'title'而不是'myEntireDataLine'。 – JoshDM

1

正在逐行读取文件。您可以使用以下

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

在这种情况下,你将不会被标题只限制的。

String API

+0

包含解决了这个问题。所有的评论给了我一个不同的方向,看看它难以让你的头脑作为一个学习者。 smit,JoshDm,jlordo感谢您的帮助:) –

+1

@MattBrookes我很高兴它的帮助。 jlordo在你的实现中正确提示。但是,如果你遇到这样的问题,你绝对可以看看''Java API DOC''。我包括在我的答案中。 – Smit

+0

根据你最终使用的答案,你应该接受一个,这样这个问题可以被关闭。 – JoshDM