我做了一个简单的实用方法来用 Java 读取文件。不幸的是,该方法似乎在运行后将文件锁定。换句话说,即使在调用方法并将其存储在 byte[] 中后,我也无法调用文件上的函数(例如 .delete())。我很确定我关闭了所有 channel 。知道为什么之后无法删除该文件吗?一个注意事项是当我调用 .deleteOnExit() 时删除文件有效。我知道我可以在 Java 7 API 中使用 Files.read() 方法,但我想知道为什么这个方法不起作用。任何建议将不胜感激。
/**
* Converts the file into a byte[]. Also Android compatible. :)
* @param The File you want to get the byte[] from.
* @return The byte[]
* @throws IOException if something goes wrong in reading the file.
*/
private byte[] mapFileIn(File infile) throws IOException{
FileInputStream fis = null;
FileChannel fc = null;
try{
fis = new FileInputStream(infile);
fc = fis.getChannel(); // Get the file's size and then map it into memory
int sz = (int)fc.size();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);
byte[] data2 = new byte[bb.remaining()];
bb.get(data2);
fc.close();
fis.close();
return data2;
}
finally{//Ensures resources are closed regardless of whether the action suceeded
try{
fis.close();
fc.close();
}
catch(Exception e){
//Does nothing
}
}
}
最佳答案
问题是 bb
还没有被 GC 清除,所以仍然有对文件的引用。
内存映射文件的主要好处是您可以避免将数据复制到 byte[] 或从中复制数据来使用它。如果最后需要一个 byte[],我建议您直接将 read() 读入 byte[]。
有一个内部方法
((DirectBuffer) bb).cleaner().clean();
释放内存映射。您必须非常确定在调用此方法后不会使用此 ByteBuffer。
关于java - 为什么此实用程序方法会使文件处于锁定状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24589488/