0

Possible Duplicate:
Java - Find a line in a file and remove

I have a code that Get id number and search for its records, if exist, display it.

I want if found, delete it record. One solution for delete a line( a user record) is create another file and copy all lines without found record. can anyone tell me another solution? (Simple solution)

my BookRecords.txt file is this:

Name        Date        Number

one   2002   22
two   2003   33
three   2004   44
four   2005   55

my Code to find :

String bookid=jTextField2.getText();
File f=new File("C:\\BookRecords.txt");
try{
    FileReader Bfr=new FileReader(f);
    BufferedReader Bbr=new BufferedReader(Bfr);
    String bs;
    while( (bs=Bbr.readLine()) != null ){
    String[] Ust=bs.split("   ");
    String Bname=Ust[0];
    String Bdate=Ust[1];
    String id = Ust[2];
    if (id.equals(bookid.trim()) 
    jLabel1.setText("Book Found,    "+ Bname + "    " + Bdate);
    break;
        }
      }
    }
catch (IOException ex) {
    ex.printStackTrace();
} 

please help to delete a Line(a Record)

Thanks.

Community
  • 1
  • 1
user1945649
  • 35
  • 1
  • 7

2 Answers2

1

Working on a single text file is - uhm - a bit strange. But I would recommend, that you create a new text file (output):

PrintWriter out = new PrintWriter(new FileWriter("output.txt"));

Only write the lines that don't match the book's ID.

while (...) {
    ...
    if (!id.equals(bookid.trim())) {
        out.println(bs);
    }
}
out.close();

Later you can rename the file, if you like.

Moritz Petersen
  • 12,902
  • 3
  • 38
  • 45
0

replace the entire line in the text file with a backspace character when found

\b

Pravin Sonawane
  • 1,803
  • 4
  • 18
  • 32