0

I have text file called BookingDetails.txt

inside the file there's a line of records

Abid  Akmal  18/11/2013  0122010875  Grooming  Zalman  5  125.0  Dog

It goes from

First name: Abid, Last name: Akmal, Date, phone number, type of services, pet name, days of stay, cost, and type of pet.

I want to create a user input function in which when the user enters the first name and the last name, the whole line is deleted. But note that it will only affect that particular line as they will be more booking entry in the text file.

This is only a part of my program that I don't know how to do. I'm stuck here basically.

The program will look like this.

Welcome to the delete menu:

Enter first name: Bla bla bla Enter last name: Bla

Then a message will come out saying record has been deleted.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
Steven Wong
  • 11
  • 1
  • 1
  • 7

1 Answers1

3

Try something like this. The code reads each line of a file. If that line doesn't contain the name, The line will be written to a temporary file. If the line contains the name, it will not be written to temp file. In the end the temp file is renamed to the original file.

File inputFile = new File("myFile.txt");   // Your file  
File tempFile = new File("myTempFile.txt");// temp file

BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

Scanner scanner = new Scanner(System.in);
System.out.println("Enter firstName");
String firstName = scanner.nextLine();
System.out.println("Enter lastName");
String lastName = scanner.nextLine();

String currentLine;

while((currentLine = reader.readLine()) != null) {

    if(currentLine.contains(firstName) 
         && currentLine.contains(lastName)) continue;

    writer.write(currentLine);
}

writer.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Thanks. I tried it out. It works but until the point when I added more and more records, the content in the text file became weird. It goes like For example.. Firstrecord, next line, Secondrecord, next line, Thirdrecord. When I deleted the Secondrecord for example. The first and the third record merged together. So as a result it will be like FirstrecordThirdrecord. – Steven Wong Nov 18 '13 at 15:39
  • Just add a `writer.newLine()` after `writer.write(currentLine)`. You could even add a second `writer.newLine()` if you want to maintain the double spacing. – Paul Samsotha Nov 18 '13 at 15:44