Reputation: 1358
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:
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;
}
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.
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()
Extra Info: The code above is part of a method called getFileByteArray(File file) and is being called like this:
public byte[] createReport(int id) {
Report report = new Report();
String filename = report.CreateReport(id);
return getFileByteArray(new File(filename));
}
Thanks
Update: I managed to fix the issue by reading the file kilobyte by kilobyte into the byte array using ByteArrayOutputStream
As a poster below mentioned, there is a known bug in Java in that Windows has issues with file mapping.
Upvotes: 12
Views: 21735
Reputation:
And translating sarumont's comment into code
This should/may work.
private static void deleteMappedFilesIfExists(Path path) throws IOException {
while (true) {
try {
Files.deleteIfExists(path);
break;
} catch (AccessDeniedException e) {
System.gc();
}
//Add delay if needed.
}
}
Upvotes: 1
Reputation: 14232
This is a known Bug in Java on Windows, please see Bug #4715154
Sun evaluated the problem and closed the bug with the following explanation:
We cannot fix this. Windows does not allow a mapped file to be deleted. This problem should be ameliorated somewhat once we fix our garbage collectors to deallocate direct buffers more promptly (see 4469299), but otherwise there's nothing we can do about this.
Upvotes: 21