从某一点读取/编辑文件

时间:2015-09-24 08:44:21

标签: java file parsing bufferedreader bufferedwriter

我目前正在尝试编写一小段需要读取文件的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 ^

1 个答案:

答案 0 :(得分:1)

您的方法是正确的,您需要阅读旧文件,进行替换并将其写回。当前算法中不正确的部分是在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");  
    }