使用java在txt文件中删除一行和它下面的两行

时间:2022-03-21 20:21:26

The problem: I need to delete a reservation. The user gives me the hour of the reservation trough a SimpleInOutDialog. Then I search with a buffered reader if the file contains that hour.

问题:我需要删除预订。用户通过SimpleInOutDialog向我提供预订时间。然后我用缓冲的阅读器搜索文件是否包含该小时。

What I need to do , is delete that line with the hour and 2 lines beneath it because there are the data of the reservation. Here's and example of the txtFile:

我需要做的是删除该行下面的小时和2行,因为有预订的数据。以下是txtFile的示例:

10:00
Niel Butaye
1
09:00
Tom Mullue
2

So I look for 10:00 and then 10:00 , Niel Butaye and 1 need to be deleted. The code that I already have is:

所以我寻找10:00然后10:00,Niel Butaye和1需要删除。我已经拥有的代码是:

public void setAnnulation() {
        //make SimpleInOutDialog      
                SimpleInOutDialog  input = new SimpleInOutDialog("Delete reservation");
                reservation= input.readString("Give the hour (hh:mm)");
            try{

            BufferedReader br = new BufferedReader(new FileReader("L:\\Documents/Informatica/6de jaar/GIP/Reservations.txt"));
            HashSet<String> hs = new HashSet<String>();
            int i = 0;
            while ((line = br.readLine()) != null)
            {
                i++;
                hs.add(br.readLine());

            }
            if(hs.contains(reservation)){
                //klant bestaat
             input.showString("The Reservation is being deleted", "");...}





            }catch (Exception e){//Catch wanneer er errors zijn
                System.err.println("Error: " + e.getMessage());}


    }

Where the "..." needs to come the code. Any help ?

代码中需要“......”的地方。有帮助吗?

1 个解决方案

#1


0  

Your approach is foul. Try to handle the file sequentially. Remember that you need to write it anyway so try this:

你的方法很糟糕。尝试按顺序处理文件。请记住,无论如何你需要写它,所以试试这个:

(open file for reading, open new file for writing)

(打开文件进行阅读,打开新文件进行写作)

  1. readLine -> String variable
  2. readLine - >字符串变量

  3. if readLine is your reservation read the next two lines without doing anything.
  4. 如果readLine是您的预订,请阅读接下来的两行而不做任何事情。

  5. if not 2) then write the line to the new file.
  6. 如果不是2)然后将该行写入新文件。

  7. flush new file and close both.
  8. 刷新新文件并关闭它们。

  9. delete old file and move new one to old name.
  10. 删除旧文件并将新文件移动到旧名称。

done.

#1


0  

Your approach is foul. Try to handle the file sequentially. Remember that you need to write it anyway so try this:

你的方法很糟糕。尝试按顺序处理文件。请记住,无论如何你需要写它,所以试试这个:

(open file for reading, open new file for writing)

(打开文件进行阅读,打开新文件进行写作)

  1. readLine -> String variable
  2. readLine - >字符串变量

  3. if readLine is your reservation read the next two lines without doing anything.
  4. 如果readLine是您的预订,请阅读接下来的两行而不做任何事情。

  5. if not 2) then write the line to the new file.
  6. 如果不是2)然后将该行写入新文件。

  7. flush new file and close both.
  8. 刷新新文件并关闭它们。

  9. delete old file and move new one to old name.
  10. 删除旧文件并将新文件移动到旧名称。

done.