title: Reading and writing to the file using same try-with-resources
body: <p>I'm using Java, and I have a method that replaces a value of a parameter in <code>configFile</code>. I use try-with-resources so that both will be closed automatically. However, I encounter an unexpected behavior - the <code>while</code> loop doesn't read anything from that file because immediately after Java enters the try-with-resources block, <code>configFile</code> becomes empty.</p>
  <pre><code>private static boolean replaceValue(String param, String newValue) throws IOException {
      try (BufferedReader br = new BufferedReader(new FileReader(configFile));
           BufferedWriter bw = new BufferedWriter(new FileWriter(configFile))) {
          String line;
          StringBuilder sb = new StringBuilder();
          boolean isParamPresent = false;
          while ((line = br.readLine()) != null) {
              if (line.startsWith(param + configDelimiter)) {
                  line = line.replaceAll(&quot;(?&lt;==).*&quot;, newValue);
                  isParamPresent = true;
              }
              sb.append(line);
              sb.append(&quot;\n&quot;);
          }
          if (isParamPresent) {
              bw.write(sb.toString());
              return true;
          }
      }
      return false;
  }
  </code></pre>
  <p>If I change to code to be like this below, it works as expected.</p>
  <pre><code>            if (isParamPresent) {
              try (BufferedWriter bw = new BufferedWriter(new FileWriter(configFile))) {
                  bw.write(sb.toString());
                  return true;
              }
  </code></pre>
  <p>I don't understand what causes <code>configFile</code> to become empty. Can someone explain what's wrong?</p>