繁体   English   中英

删除文本文件中的特定行

[英]Remove specific line in text file

我有一个.txt 文件inventory.txt 它包含

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

我想创建一种方法,通过输入catscats, 20, 30来删除这些行之一,比方说cats

我的代码提示用户输入removedItem ,读取inventory.txt ,修剪每一行,并检查trimmedLine是否等于removedItem ,然后continue并写入deleteditems.txt读取的每一line ,不包括trimmedLine 然后我关闭writerreader ,删除原来的inventory.txt ,并将deleteditems.txt重命名为inventory.txt 但是,它什么也没做,编译后该行仍然存在。

代码:

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);

    }

Output:

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

你在做什么有两个问题:

  • 您正在将整行与“等于”的输入进行比较......为了匹配,用户不能只输入“猫”,他们需要输入“猫,20、30”,因为那是一行包含什么。
  • 即使匹配,您仍在向 output 文件写入“行”

您可以这样修复它:

 while((line = reader.readLine()) != null) {
            String trimmedLine = line.trim();
            if(!trimmedLine.startsWith(removedLine)) {

               writer.write(line + 
                  System.getProperty("line.separator"));
            }
        }

如果它不以输入开头,这将只写该行。

作为旁注,您应该考虑使用“尝试使用资源”语句来打开您的阅读器/编写器,以确保即使在发生异常时也能正确清理。

您正在尝试检查是否与 .equals() 完全匹配

尝试使用.contains(CharSequence) 或.startsWith()

        String newInventory = ""; 

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

           newInventory += line;
        }

        FileOutputStream fout = new FileOutputSteam("src/inventory.txt");
        fout.write(newInventory.getBytes());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM