删除文本文件中的特定行

I have a .txt file, inventory.txt. it contains

banana, 1, 15
dog, 1, 15
cats, 20, 30

I would like to create a method that would delete one of these lines, let's say the cats line, by either inputting cats or cats, 20, 30

My code prompts the user for removedItem, reads the inventory.txt, trims each line, and checks if trimmedLine is equal to removedItem, then continue and writes to deleteditems.txt every line read excluding the trimmedLine. I then close both writer and reader, delete the original inventory.txt, and rename deleteditems.txt to inventory.txt. However, it does not do anything, and the line remains after compiling.

码:

public void removeItems() throws IOException {

        String line;

        File inventory = new File("src/inventory.txt");
        File temp = new File("src/deleteditems.txt");

        BufferedReader reader = new BufferedReader(new FileReader("src/inventory.txt"));
        BufferedWriter writer = new BufferedWriter(new FileWriter("src/deleteditems.txt"));

        displayInventory();

        temp.createNewFile();

        System.out.println("what item do you want to remove");
        String removedLine = scan.next();

        while((line = reader.readLine()) != null) {
            String trimmedLine = line.trim();
            if(trimmedLine.equals(removedLine)) {
                trimmedLine = "";
            }
            writer.write(line + System.getProperty("line.separator"));
        }
        reader.close(); 
        writer.close(); 
        inventory.delete();
        temp.renameTo(inventory);

    }

输出:

banana, 1, 15
dog, 1, 15
cats, 20, 30
what item do you want to remove
cats, 20, 30

编译后的文本文件:

banana, 1, 15
dog, 1, 15
cats, 20, 30
评论
  • comnis
    comnis 回复

    您所做的工作有两个问题:

    • 您正在将整行与带有“等于”的输入进行比较。
    • 为了匹配,用户不仅需要输入“猫”,还需要
    • 输入“ cats,20,30”,因为那是一行所包含的内容。
    • 即使匹配,您仍将“行”写入输出文件

    您可以这样解决:

     while((line = reader.readLine()) != null) {
                String trimmedLine = line.trim();
                if(!trimmedLine.startsWith(removedLine)) {
    
                   writer.write(line + 
                      System.getProperty("line.separator"));
                }
            }
    

    如果它不是以输入开头,则只会写该行。

    As a side-note, you should look at using the "try with resources" statement to open your reader/writer to ensure things get cleaned up properly even in the event of an exception.