如何使用扫描仪使用Java从文本文件中删除一行 [英] How to delete a line from a text file with java using scanner

查看:44
本文介绍了如何使用扫描仪使用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);

这篇关于如何使用扫描仪使用Java从文本文件中删除一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆