【问题标题】:How to remove line from txt file with buffered reader java [duplicate]如何使用缓冲阅读器java从txt文件中删除行[重复]
【发布时间】:2025-12-19 16:50:06
【问题描述】:

我需要从 txt 文件 a 中删除行

FileReader fr= new FileReader("Name3.txt");

BufferedReader br = new BufferedReader(fr);

String str = br.readLine();

br.close();

我不知道代码的继续。

【问题讨论】:

  • 当你说“删除”时,你的意思是你要修改底层文件吗?读者不会那样做。
  • 您要删除哪一行?最后一行?第一行?特定的行?所有的线??
  • 不能使用BufferedReader 做到这一点。奇怪的标题。

标签: java string bufferedreader filereader


【解决方案1】:

您可以读取所有行并将它们存储在列表中。在存储所有行时,假设您知道要删除的行,只需检查您不想存储的行,然后跳过它们。然后将列表内容写入文件。

    //This is the file you are reading from/writing to
    File file = new File("file.txt");
    //Creates a reader for the file
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line = "";

    //This is your buffer, where you are writing all your lines to
    List<String> fileContents = new ArrayList<String>();

    //loop through each line
    while ((line = br.readLine()) != null) {
        //if the line we're on contains the text we don't want to add, skip it
        if (line.contains("TEXT_TO_IGNORE")) {
            //skip
            continue;
        }
        //if we get here, we assume that we want the text, so add it
        fileContents.add(line);
    }

    //close our reader so we can re-use the file
    br.close();

    //create a writer
    BufferedWriter bw = new BufferedWriter(new FileWriter(file));

    //loop through our buffer
    for (String s : fileContents) {
        //write the line to our file
        bw.write(s);
        bw.newLine();
    }

    //close the writer
    bw.close();

【讨论】:

  • 我看不懂你的代码,你能解释一下吗
  • 好的,我已经在代码中添加了cmets
  • 在Java 8中,整个阅读段基本可以替换成List&lt;String&gt; fileContents = Files.lines(file.toPath()).filter(line -&gt; !line.contains("TEXT_TO_IGNORE")).collect(Collectors.toCollection(ArrayList&lt;String&gt;::new));