在文件中查找一行并将其删除 [英] Find a line in a file and remove it

查看:154
本文介绍了在文件中查找一行并将其删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for a small code snippet that will find a line in file and remove that line (not content but line) but could not find. So for example I have in a file following:

myFile.txt

aaa
bbb
ccc
ddd

需要这样的函数: public void removeLine(String lineContent),如果我传递
removeLine( bbb),我得到这样的文件:

Need to have a function like this: public void removeLine(String lineContent), and if I pass removeLine("bbb"), I get file like this:

myFile.txt:

aaa
ccc
ddd


推荐答案

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

This solution may not be optimal or pretty, but it works. It reads in an input file line by line, writing each line out to a temporary output file. Whenever it encounters a line that matches what you are looking for, it skips writing that one out. It then renames the output file. I have omitted error handling, closing of readers/writers, etc. from the example. I also assume there is no leading or trailing whitespace in the line you are looking for. Change the code around trim() as needed so you can find a match.

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

这篇关于在文件中查找一行并将其删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆