title: file overwrite in java -- user-mapped section open error
body: <p>The following function in a java program is written with the intent to read from a file and overwrite back to the same file after.</p>
  
  <pre><code>public static void readOverWrite(File dir) throws IOException {
      for (File f : dir.listFiles()) {
          String[] data = readFile(f).split("\n");
          try (BufferedWriter writer = new BufferedWriter(new FileWriter(f))) {
              for (int i = 0; i &lt; data.length; i++) {
                  writer.write((data[i]+"\n"));
              }
              writer.close();
          }
      }
  } 
  </code></pre>
  
  <p>The error message on trying to run the program is:</p>
  
  <pre><code>Exception in thread "main" java.io.FileNotFoundException: ..\..\data\AQtxt\APW19980807.0261.tml (The requested operation cannot be performed on a file with a user-mapped section open)
      at java.io.FileOutputStream.open(Native Method)
      at java.io.FileOutputStream.&lt;init&gt;(Unknown Source)
      at java.io.FileOutputStream.&lt;init&gt;(Unknown Source)
      at java.io.FileWriter.&lt;init&gt;(Unknown Source)
      at General.SplitCreationDate.splitLine(SplitCreationDate.java:37)
      at General.SplitCreationDate.main(SplitCreationDate.java:53)
  </code></pre>
  
  <p>Request help in resolving the error.</p>
  
  <hr>
  
  <p>Code for readFile</p>
  
  <pre><code>protected static String readFile(File fullPath) throws IOException {
      try(FileInputStream stream = new FileInputStream(fullPath)) {
          FileChannel fc = stream.getChannel();
          MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
          stream.close();
          return Charset.defaultCharset().decode(bb).toString();
      }
  } 
  </code></pre>
  
  <hr>
  
  <p>Read in another thread that this is a windows issue and so MappedByteBuffer in the readFile method was the cause of the problem. Re-wrote the readFile method as below. It works!</p>
  
  <pre><code>protected static String readFile(File fullPath) throws IOException {
      String string = "";
      try (BufferedReader in = new BufferedReader(new FileReader(fullPath))) {
          String str;
          while ((str = in.readLine()) != null) {
              string += str + "\n";
          }
      }
      return string;
  } 
  </code></pre>