在文件中查找一行并将其删除

2022-08-31 14:05:46

我正在寻找一个小代码片段,它将在文件中找到一行并删除该行(不是内容,而是行),但找不到。例如,我在一个文件中有以下内容:

我的文件.txt

aaa
bbb
ccc
ddd

需要有一个这样的函数:,如果我通过,我会得到这样的文件:public void removeLine(String lineContent)removeLine("bbb")

我的文件.txt:

aaa
ccc
ddd

答案 1

此解决方案可能不是最佳或漂亮的,但它有效。它逐行读取输入文件,将每一行写出到临时输出文件中。每当它遇到与您正在寻找的内容匹配的行时,它就会跳过将该行写出来。然后,它将重命名输出文件。我从示例中省略了错误处理,关闭读取器/写入器等。我还假设您要查找的行中没有前导或尾随空格。根据需要更改 trim() 周围的代码,以便找到匹配项。

File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");

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

String lineToRemove = "bbb";
String currentLine;

while((currentLine = reader.readLine()) != null) {
    // trim newline when comparing with lineToRemove
    String trimmedLine = currentLine.trim();
    if(trimmedLine.equals(lineToRemove)) continue;
    writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close(); 
reader.close(); 
boolean successful = tempFile.renameTo(inputFile);

答案 2
    public void removeLineFromFile(String file, String lineToRemove) {

    try {

      File inFile = new File(file);

      if (!inFile.isFile()) {
        System.out.println("Parameter is not an existing file");
        return;
      }

      //Construct the new file that will later be renamed to the original filename.
      File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

      BufferedReader br = new BufferedReader(new FileReader(file));
      PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

      String line = null;

      //Read from the original file and write to the new
      //unless content matches data to be removed.
      while ((line = br.readLine()) != null) {

        if (!line.trim().equals(lineToRemove)) {

          pw.println(line);
          pw.flush();
        }
      }
      pw.close();
      br.close();

      //Delete the original file
      if (!inFile.delete()) {
        System.out.println("Could not delete file");
        return;
      }

      //Rename the new file to the filename the original file had.
      if (!tempFile.renameTo(inFile))
        System.out.println("Could not rename file");

    }
    catch (FileNotFoundException ex) {
      ex.printStackTrace();
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
  }

这是我在互联网上找到的。