简体   繁体   English

如何使用扫描仪使用Java从文本文件中删除一行

[英]How to delete a line from a text file with java using scanner

I have text file called BookingDetails.txt 我有一个名为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 输入姓氏:Bla bla bla输入姓氏: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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM