【问题标题】:How to replace a line with a new line using Java如何使用 Java 用新行替换一行
【发布时间】:2016-04-23 01:39:30
【问题描述】:

我使用缓冲区阅读器解析整个文件。如果找到 Oranges: 模式,我想用 ApplesAndOranges 替换它。

try (BufferedReader br = new BufferedReader(new FileReader(resourcesFilePath))) {

            String line;

            while ((line = br.readLine()) != null) {
if (line.startsWith("Oranges:")){
                        int startIndex = line.indexOf(":");
                        line = line.substring(startIndex + 2);
                        String updatedLine = "ApplesAndOranges";
                        updateLine(line,  updatedLine);

我调用一个方法 updateLine 并传递我的原始行以及更新后的行值。

private static void updateLine(String toUpdate, String updated) throws IOException {
    BufferedReader file = new BufferedReader(new FileReader(resourcesFilePath));
    PrintWriter writer = new PrintWriter(new File(resourcesFilePath+".out"), "UTF-8");
    String line;

    while ((line = file.readLine()) != null)
    {
        line = line.replace(toUpdate, updated);
        writer.println(line);
    }
    file.close();
    if (writer.checkError())
        throw new IOException("Can't Write To File"+ resourcesFilePath);
    writer.close();
}

要更新文件,我必须用不同的名称保存它(resourcesFilePath+".out")。如果我使用原始文件名,保存的版本将变为空白。
所以这是我的问题,如何在不丢失任何数据的情况下用原始文件中的任何值替换一行。

【问题讨论】:

  • 读取每一行,处理它,写入一个新文件。完成后,删除旧文件并将新文件重命名到它的位置
  • 你需要用新行重写文件。你不能使用 line.replace
  • 感谢 MadProgrammer 的输入。我使用了 Array 来重写数据。我不确定这是否是过度杀戮,因为我只需要替换该资源文件中的一行。请发布您的评论作为答案以相应地接受它。您能否确认在不重写整个文件的情况下无法替换该行?

标签: java bufferedreader filewriter


【解决方案1】:

为此,您需要像这样使用正则表达式 (RegExp):

str = str.replaceAll("^Orange:(.*)", "OrangeAndApples:$1");

这是一个例子,也许它不是你想要的,但在这里,在第一个参数中,parentesis 中的表达式称为捕获组。找到的表达式将被第二个参数替换,$1 将被捕获组的值替换。在我们的示例中,行首的 Orange:Hello 将替换为 OrangeAndApples:Hello。

在您的代码中,您每行创建一个文件……也许内联子方法会更好。

try (
    BufferedReader br = new BufferedReader(new FileReader(resourcesFilePath));
    BufferedWriter writer = Files.newBufferedWriter(outputFilePath, charset);
) {
    String line;

    while ((line = br.readLine()) != null) {
        String repl = line.replaceAll("Orange:(.*)","OrangeAndApples:$1");
        writer.writeln(repl);
    }
}

【讨论】:

  • 感谢您的意见!但我的目标是用新数据覆盖原始文件。在您的示例中,您将数据写入 outputfilePath。我想把它写到resourcesFilePath。这似乎可以解决问题,但如果我试图覆盖原始文件,文件就会变为空白。
【解决方案2】:

在原始决赛中重写所有内容的最简单方法是读取所有内容 - 更改您想要更改的任何内容并关闭流。然后再次打开文件,然后用你想要的数据覆盖文件及其所有行。

【讨论】:

    【解决方案3】:

    您可以使用 RandomAccessFile 写入文件,并使用 nio.Files 从中读取字节。在这种情况下,我把它作为一个字符串。

    您也可以使用 RandomAccessFile 读取文件,但我认为这样做更容易。

    import java.io.RandomAccessFile;
    import java.io.File;
    import java.io.IOException;
    import java.nio.file.*;
    
    public void replace(File file){
        try {
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        Path p = Paths.get(file.toURI());
        String line = new String(Files.readAllBytes(p));
        if(line.startsWith("Oranges:")){
        line.replaceAll("Oranges:", "ApplesandOranges:");
            raf.writeUTF(line);
        }
        raf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-27
      • 2022-07-20
      • 2015-02-16
      • 2018-01-14
      • 2011-07-28
      • 2022-01-09
      • 1970-01-01
      • 2010-10-16
      相关资源
      最近更新 更多