如何从文本文件中删除特定文本?

时间:2015-12-06 01:14:10

标签: java

我有一个客户列表,其中包含:客户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;
}

任何帮助都会很棒......谢谢。

1 个答案:

答案 0 :(得分:0)

正如@ 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;