如何动态地将文本附加到文本文件中

时间:2021-10-12 03:05:54
[12]
key1=val1
key2=val2
key3=val3
key4=val4
key5=val5
[13]
key1=val1
key2=val2
key3=val3
key4=val4
key5=xyz
[14]
key1=val1
key2=val2
key3=val3
key4=val4
key5=val5

I want to update key5=val5 where [13].

我想更新key5 = val5,其中[13]。

 try {
         br = new BufferedReader(new FileReader(oldFileName));
         bw = new BufferedWriter(new FileWriter(tmpFileName));
         String line;
         while ((line = br.readLine()) != null) {
             System.out.println(line);

            if (line.contains("[13]"))
            {
                while (line.contains("key5")) {
                      if (line.contains("key5"))
                      {
                           line = line.replace("key5", "key5= Val5");
                           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) {
            //
         }
      }

3 个解决方案

#1


2  

This block of code is problematic:

这段代码存在问题:

if (line.contains("[13]"))
{
    while (line.contains("key5")) {
    //etc....

Because there are NO lines which contain both [13] and key5 (they are on separate lines), so the while loop will NEVER be entered.

因为没有包含[13]和key5(它们在不同的行上)的行,所以永远不会输入while循环。

Instead, when the line [13] is encountered, it's necessary to remember it and store the flag in a boolean, something like the following:

相反,当遇到第[13]行时,必须记住它并将标志存储在布尔值中,如下所示:

boolean in13 = false;

//... other lines...


if (line.equals("[13]")) {
    in13 = true;
} else if (line.startsWith("[")) {
    in13 = false;   //another block started, clear flag
}

if (in13 && line.startsWith("key5=")) {
    // you've found it
}

#2


1  

You really need to step through your logic in your head; in your code:

你真的需要逐步掌握你的逻辑;在你的代码中:

if (line.contains("[13]")) {
    while (line.contains("key5")) {
        if (line.contains("key5")) {
            line = line.replace("key5", "key5= Val5");
            bw.write(line+"\n");
        }
    }
}

Try writing this out on a piece of paper or something and following it. Look at your while (line.contains("key5")) loop for example. If the line contains "[13]" then it does not contain "key5" and your loop does not even run once. There are many other problems as well (such as the fact that you're only attempting to write one line back out, as another person mentioned in the comments, or that you're not reading any more lines inside your loop, among other issues). For these types of things, work out precisely what you want to do, then write code to match. It looks like you want to do the following:

尝试在一张纸或其他东西上写下来然后跟着它。例如,看看你的while(line.contains(“key5”))循环。如果该行包含“[13]”,则它不包含“key5”,并且您的循环甚至不会运行一次。还有许多其他问题(例如,您只是试图写回一行,正如评论中提到的另一个人,或者您在循环中不再读取任何行,以及其他问题) )。对于这些类型的东西,准确地计算出你想要做的事情,然后编写代码来匹配。看起来您想要执行以下操作:

  1. Search for the line "[13]". Once found...
  2. 搜索“[13]”行。一旦找到......

  3. Search for a line starting with "key5=", but stop when a new section (starting with "[") is encountered. If that is found:
  4. 搜索以“key5 =”开头的行,但在遇到新部分(以“[”开头)时停止。如果找到了:

  5. Replace that line with "key5=" + new value.
  6. 用“key5 =”+新值替换该行。

And for each line you touch that you do not replace, you'd have to write it back out (although a general formula here, barring memory constraints, is to parse/load, then modify, then write).

对于你没有替换的每一行,你必须把它写回来(虽然这里的通用公式,除了内存约束,是解析/加载,然后修改,然后写)。

So you'll want your code to do that.

所以你会希望你的代码能够做到这一点。

Also note that some INI file parser implementations (presuming you are treating this as an INI file) ignore whitespace and/or case in the key and section names, so depending on the source of your file, you may want to take that into account.

另请注意,一些INI文件解析器实现(假设您将其视为INI文件)忽略键和节名称中的空格和/或大小写,因此根据文件的来源,您可能需要考虑这一点。

By the way, perhaps consider using an INI file handling library such as ini4j, where you can load the file and replace keys directly. See What is the easiest way to parse an INI file in Java?.

顺便说一句,也许可以考虑使用INI文件处理库,例如ini4j,您可以在其中加载文件并直接替换密钥。请参阅在Java中解析INI文件的最简单方法是什么?

#3


0  

This part looks wrong:

这部分看起来不对:

while (line.contains("key5")) {
    if (line.contains("key5"))

I assume that NOT operator is missing in loop condition

我假设在循环条件下缺少NOT运算符

#1


2  

This block of code is problematic:

这段代码存在问题:

if (line.contains("[13]"))
{
    while (line.contains("key5")) {
    //etc....

Because there are NO lines which contain both [13] and key5 (they are on separate lines), so the while loop will NEVER be entered.

因为没有包含[13]和key5(它们在不同的行上)的行,所以永远不会输入while循环。

Instead, when the line [13] is encountered, it's necessary to remember it and store the flag in a boolean, something like the following:

相反,当遇到第[13]行时,必须记住它并将标志存储在布尔值中,如下所示:

boolean in13 = false;

//... other lines...


if (line.equals("[13]")) {
    in13 = true;
} else if (line.startsWith("[")) {
    in13 = false;   //another block started, clear flag
}

if (in13 && line.startsWith("key5=")) {
    // you've found it
}

#2


1  

You really need to step through your logic in your head; in your code:

你真的需要逐步掌握你的逻辑;在你的代码中:

if (line.contains("[13]")) {
    while (line.contains("key5")) {
        if (line.contains("key5")) {
            line = line.replace("key5", "key5= Val5");
            bw.write(line+"\n");
        }
    }
}

Try writing this out on a piece of paper or something and following it. Look at your while (line.contains("key5")) loop for example. If the line contains "[13]" then it does not contain "key5" and your loop does not even run once. There are many other problems as well (such as the fact that you're only attempting to write one line back out, as another person mentioned in the comments, or that you're not reading any more lines inside your loop, among other issues). For these types of things, work out precisely what you want to do, then write code to match. It looks like you want to do the following:

尝试在一张纸或其他东西上写下来然后跟着它。例如,看看你的while(line.contains(“key5”))循环。如果该行包含“[13]”,则它不包含“key5”,并且您的循环甚至不会运行一次。还有许多其他问题(例如,您只是试图写回一行,正如评论中提到的另一个人,或者您在循环中不再读取任何行,以及其他问题) )。对于这些类型的东西,准确地计算出你想要做的事情,然后编写代码来匹配。看起来您想要执行以下操作:

  1. Search for the line "[13]". Once found...
  2. 搜索“[13]”行。一旦找到......

  3. Search for a line starting with "key5=", but stop when a new section (starting with "[") is encountered. If that is found:
  4. 搜索以“key5 =”开头的行,但在遇到新部分(以“[”开头)时停止。如果找到了:

  5. Replace that line with "key5=" + new value.
  6. 用“key5 =”+新值替换该行。

And for each line you touch that you do not replace, you'd have to write it back out (although a general formula here, barring memory constraints, is to parse/load, then modify, then write).

对于你没有替换的每一行,你必须把它写回来(虽然这里的通用公式,除了内存约束,是解析/加载,然后修改,然后写)。

So you'll want your code to do that.

所以你会希望你的代码能够做到这一点。

Also note that some INI file parser implementations (presuming you are treating this as an INI file) ignore whitespace and/or case in the key and section names, so depending on the source of your file, you may want to take that into account.

另请注意,一些INI文件解析器实现(假设您将其视为INI文件)忽略键和节名称中的空格和/或大小写,因此根据文件的来源,您可能需要考虑这一点。

By the way, perhaps consider using an INI file handling library such as ini4j, where you can load the file and replace keys directly. See What is the easiest way to parse an INI file in Java?.

顺便说一句,也许可以考虑使用INI文件处理库,例如ini4j,您可以在其中加载文件并直接替换密钥。请参阅在Java中解析INI文件的最简单方法是什么?

#3


0  

This part looks wrong:

这部分看起来不对:

while (line.contains("key5")) {
    if (line.contains("key5"))

I assume that NOT operator is missing in loop condition

我假设在循环条件下缺少NOT运算符