Reading/editing某点的文件

Reading/editing a file from a certain point

我目前正在尝试编写一小段 Java 需要通读文件,搜索要更改的特定行。问题是要更改的行在文件中不是唯一的,因为它是 XML 类结构的一部分,因此嵌套在另一个标记中。

例如:

<tag1>Tag Text</tag1>
    <example>Value</example>

<tag2>Tag Text</tag2>
    <example>Value</example> //Want to change only this Value.

<tag3>Tag Text</tag3>
    <example>Value</example>

在此示例中,我只想更改 <tag2> 下示例标记中的值而不更改其他值。

所以我首先尝试搜索 <tag2>,找到后我搜索 <value>,编辑该值,然后保持文件的其余部分不变。

目前我正在使用 BufferedReader/Writer 将文件复制到一个临时文件,更改一个值,然后删除旧文件,用新文件替换它。

查看下面的代码:

public class Replace {
   public static void main(String[] args) {
     new Replace().replace();
   }

   public void replace() {

    //All input data to be changed, testing purposes.
    String rootFolder = "Some root";
    String fileName = "some filename";
    String newValue = "<Value>New Value</Value>";

    //Strings to find location in the file that needs to be amended.
    String firstFileLine = "<tag2>";
    String secondFileLine = "<Value>";

    String oldFileName = rootFolder + fileName;
    String tmpFileName = "temp.txt";

      BufferedReader br = null;
      BufferedWriter bw = null;
      try {
         br = new BufferedReader(new FileReader(oldFileName));
         bw = new BufferedWriter(new FileWriter(tmpFileName));
         String line, secondLine;
         while ((line = br.readLine()) != null) {
            if (line.contains(firstFileLine)){
            //This is an attempt to try solve it, but this still replaced all <Value> tags in the file
               while ((secondLine = br.readLine()) != null) {
                    if (secondLine.contains(secondFileLine))
                        secondLine = secondLine.replace(secondFileLine, newValue);
                    bw.write(secondLine+"\n");  
                }
            }
            bw.write(line+"\n");           
         }
      } catch (Exception e) {
         return;
      } finally {
         try {
            if(br != null)
               br.close();
         } catch (IOException e) {
            //
         }
         try {
            if(bw != null)
               bw.close();
         } catch (IOException e) {
            //
         }
      }
      // Once everything is complete, delete old file..
      File oldFile = new File(oldFileName);
      oldFile.delete();

      // And rename tmp file's name to old file name
      File newFile = new File(tmpFileName);
      newFile.renameTo(oldFile);

   }
}

这是解决此问题的最佳方式吗?也欢迎任何其他建议!

先谢谢大家了!

W

你的做法是正确的,你需要读取旧文件,替换并写回。您当前算法中不正确的部分是在 while 循环中,您需要在到达 tag2 末尾时停止。

此外,如果内容是 XML,您应该考虑使用 XML 解析器来执行此操作。

    while ((secondLine = br.readLine()) != null) {

        if (secondLine.contains(endOfFirstLine)) {
            bw.write(secondLine+"\n"); 
            break;
        }

        if (secondLine.contains(secondFileLine))
            secondLine = secondLine.replace(secondFileLine, newValue);
        bw.write(secondLine+"\n");  
    }