Java FileChannel 保持锁定文件

问题描述

希望有人能阐明我做错了什么。

我有一个创建 FileInputStream 的 DataLoader 类。由于 FileInputStream 实现了 Closeable,我创建了该实例作为 t​​ry 块的一部分。

然后我将新创建的流传递给 DataManager 类。这个类打开一个文件通道并将数据读入一个单例类,将所有数据存储到内存块中。由于 FileChannel 也实现了 Closeable,我也在 try 块中实例化了它

然后我从单个线程调用此代码以检查是否有任何文件更改,当发生这种情况时,会创建一个新的 DataLoader 实例来重建内存块。但是由于文件锁定,这经常失败。此代码是在 Windows 10 上运行的 Java 1.8 标准应用程序的一部分。我是否错误地假设文件通道和文件输入流都关闭了?我添加了代码来调用两个类中的 close 方法,但没有成功。

任何帮助将不胜感激。提前致谢。

public class DataManager {

    public DataManager(FileInputStream in) throws IOException {
        fromInputStream(in);
    }

    public final void fromInputStream(FileInputStream in) throws IOException {
        try (FileChannel ch = in.getChannel()) {
            MappedByteBuffer mb = ch.map(MapMode.READ_ONLY,ch.position(),ch.size());
            readData(mb); //reads mapped buffer into a byte array,e.g.: mb.get(barray,1000);
        }
    }

}

public class DataLoader {

    public DataLoader(File binFile) throws FileNotFoundException,IOException {
        try (FileInputStream in = new FileInputStream(binFile)) {
            DataManager d = new DataManager(in);
        } catch (Exception e) {
            LOG.error("Something went wrong while loading data.",e);
        }
    }

}

解决方法

正如评论中所建议的,该问题依赖于 Windows 对 FileChannel 的使用有些严格。我用 InputStream 替换了所有与 FileChannel 相关的代码,锁定行为消失了。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...