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

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

问题描述

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

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天全站免登陆