Note that there are some explanatory texts on larger screens.

plurals
  1. PORelease Java file lock in Windows
    text
    copied!<p>I'm having some problems deleting a file in Windows with java. For some reason, java is keeping a lock on my file, and I don't know why. Here is my code:</p> <pre><code>private byte[] getFileByteArray(File file) { try { RandomAccessFile raf = new RandomAccessFile(file, "r"); FileChannel channel = raf.getChannel(); try { ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); byte[] bt = new byte[buffer.remaining()]; buffer.get(bt); channel.close(); raf.close(); file.delete(); return bt; } catch (Exception ex) { //Logger.getLogger(ConnectionImpl.class.getName()).log(Level.SEVERE, null, ex); System.out.println(ex.toString()); } } catch (FileNotFoundException ex) { Logger.getLogger(ConnectionImpl.class.getName()).log(Level.SEVERE, null, ex); } return null; } </code></pre> <p>file.delete(), as well as trying manually in Explorer refuses to delete the file as it's still in use. All seems well in Linux though.</p> <p>Am I missing a close() somehwhere? I can confirm that the method which makes the file in the first place is closing the file, as I can delete the file before running the above code using file.delete()</p> <p><strong>Extra Info:</strong> The code above is part of a method called getFileByteArray(File file) and is being called like this:</p> <pre><code>public byte[] createReport(int id) { Report report = new Report(); String filename = report.CreateReport(id); return getFileByteArray(new File(filename)); } </code></pre> <p>Thanks</p> <p><strong>Update:</strong> I managed to fix the issue by reading the file kilobyte by kilobyte into the byte array using ByteArrayOutputStream</p> <p>As a poster below mentioned, there is a known bug in Java in that Windows has issues with file mapping.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload