【问题标题】:Replacing a line in a new textfile替换新文本文件中的一行
【发布时间】:2014-05-23 14:41:23
【问题描述】:

我有一个包含几行的文本文件。

Line 1
Line 2
Line 3
Line 4
...

例如,我正在尝试用新句子替换第 3 行。

我尝试使用下面的代码,但没有替换它,它只是在它旁边添加了新句子以及文本的其余部分。我需要将其删除并将新句子放在同一位置,然后继续编写其余的行。我应该解决什么问题?

try {
    PrintWriter out = new PrintWriter(new FileWriter(filenew, true));
    Scanner scanner = new Scanner(file);

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if (line.contains(line 2)) {        
            line = line.replaceAll("", "new sentence");
        }  
        out.write(line);
        out.write("\n");
    }   

    out.flush();
    out.close();
    scanner.close();
} 
catch (IOException e)  {
    e.printStackTrace();
}

提前致谢!

【问题讨论】:

    标签: java replace java.util.scanner printwriter


    【解决方案1】:

    您正在寻找的循环类似于

    String targetText = "... the text to search";
    String replacement = "The new text";
    PrintWriter out = mkPrintWriter(/*...*/);
    
    while (in.hasNextLine()) {
      String line = in.nextLine();
      if (line.equals(targetText)) {
        out.println(replacement);
      } else {
        out.println(line);
      }
    }
    

    请注意,输出文件是临时资源。处理完成后,您可以取消链接旧文件并重命名临时文件。

    【讨论】:

    • 这在我的情况下无法正常工作,因为它不会重新换行。它只是放置新行。我需要用新的替换 if 条件中的行。我想使用替换方法,这样更准确
    • @user3211165 你能举个例子吗?
    【解决方案2】:

    改变

    line = line.replaceAll("", "new sentence");
    

    line = line.replaceAll(line 2, "new sentence");
    

    【讨论】:

      猜你喜欢
      • 2018-11-24
      • 2012-03-19
      • 2016-08-08
      • 1970-01-01
      • 2016-06-22
      • 2014-06-28
      • 2013-09-04
      相关资源
      最近更新 更多