Reputation: 11
I am trying to delete specific record from File, but every time I run it deletes the whole file. Can anyone please tell where the bug is?
I have added temp db and also the methods are correct. There is some what problem with the logic of the loop. Kindly help me. Thank you!
public void DeleteRecordByID() throws IOException {
Scanner strInput = new Scanner(System.in);
String ID, record;
File tempDB = new File("employees.txt");
File db = new File("employees.txt");
BufferedReader br = new BufferedReader( new FileReader( db ) );
BufferedWriter bw = new BufferedWriter( new FileWriter( tempDB ) );
System.out.println("\t\t Delete Employee Record\n");
System.out.println("Enter the Employee ID: ");
ID = strInput.nextLine();
while( ( record = br.readLine() ) != null ) {
if( record.contains(ID) )
continue;
bw.write(record);
bw.flush();
bw.newLine();
}
br.close();
bw.close();
db.delete();
tempDB.renameTo(db);
}
Upvotes: 0
Views: 3038
Reputation: 338
You should create a temporary file in which you write the data. After that, you can delete the original file, then rename the temporary file to the original.
Upvotes: 0
Reputation: 4667
You should use two different file names, one for reading and one for writing.
Upvotes: 1