java - 为什么此实用程序方法会使文件处于锁定状态?

标签 java file file-io locking

我做了一个简单的实用方法来用 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/

相关文章:

java - 使用 Spring 与 jar 相关的文件

file - 如何在 Linux 和 Windows 上从 std::fs 支持的任何文件系统复制文件元数据?

mysql - 如何将一个大表导出为 50 个较小的 csv 文件,每个文件包含 100,000 条记录

c# 在不使用 using{} 的情况下写入文件

python - 我如何在 python 中的文件的特定列中写入一些值/字符串

java - 重置游戏以在 Java 中重新开始

java - Android Studio - 从 Google Places Details API 电话号码解析 JSON,首次运行时给出 null

java - 解析 MHTML 时出现问题

java - Neo4j java api : Transactions, 多处理和线程安全

java - 如何读取 Word 或 Txt 类型文件中字符串的 X 和 Y 坐标?