簡體   English   中英

如何從文本文件中刪除特定文本?

[英]How do I remove specific text from a text file?

我有一個包含以下內容的客戶列表:客戶ID,客戶名稱,客戶電話和客戶電子郵件。 我希望能夠通過輸入客戶名稱和/或ID從文本文件列表中刪除客戶。 這是我目前所擁有的:

  public static List<Customer> removeCustomer (List<Customer> customers)  throws IOException {
  File inputFile = new File("customers.txt");    
  File tempFile = new File("tempcustomers.txt");

  BufferedReader reader = new BufferedReader(new FileReader(inputFile));
  BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

 Scanner scanner = new Scanner(System.in);
  System.out.println("Enter Customer ID");
  String newCustomerId = scanner.nextLine();
  System.out.println("Enter Customer Name");
  String customerName = scanner.nextLine();

  String currentLine;

    while((currentLine = reader.readLine()) != null) {

      if(currentLine.contains(newCustomerId) 
         && (currentLine.contains(customerName))) continue;

     writer.write(currentLine);


 writer.close();
 boolean successful = tempFile.renameTo(inputFile);
 System.out.println(successful);
    }
 return customers;
}

任何幫助都將是驚人的..謝謝。

正如@ user1909791已經提到的那樣,您將在第一次讀取后關閉寫入。 這是您應該擁有的:

while((currentLine = reader.readLine()) != null) {
    if(currentLine.contains(newCustomerId) 
              && (currentLine.contains(customerName))) continue;

     writer.write(currentLine);
}

writer.close();
reader.close();

// Delete the current customers.txt file then rename the
// tempcustomers.txt File to customers.txt...
boolean successful = false;
if (inputFile.delete()) { successful = tempFile.renameTo(inputFile); }

System.out.println(successful);
...........................................
...... code to refill customers List ......
...........................................
return customers;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM