如何使用扫描仪使用Java从文本文件中删除一行
我有一个名为BookingDetails.txt的文本文件
I have text file called BookingDetails.txt
文件内有一行记录
Abid Akmal 18/11/2013 0122010875 Grooming Zalman 5 125.0 Dog
它来自
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.
程序将如下所示.
欢迎使用删除菜单:
输入名字:Bla bla bla 输入姓氏:Bla
Enter first name: Bla bla bla Enter last name: Bla
然后会出现一条消息,说明记录已被删除.
Then a message will come out saying record has been deleted.
尝试类似的方法.该代码读取文件的每一行.如果该行不包含名称,则该行将被写入临时文件.如果该行包含名称,则不会将其写入临时文件.最后,临时文件被重命名为原始文件.
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);