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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20048633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:41:10  来源:igfitidea点击:

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

javajava.util.scanner

提问by Steven Wong

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.

然后会出现一条消息,说记录已被删除。

采纳答案by Paul Samsotha

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);