加入收藏 | 设为首页 | 会员中心 | 我要投稿 常州站长网 (https://www.0519zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 搭建环境 > Windows > 正文

在Windows中发布Java文件锁

发布时间:2020-12-30 20:19:06 所属栏目:Windows 来源:网络整理
导读:我在 Windows中使用java删除文件有一些问题.由于某种原因,java正在锁定我的文件,我不知道为什么.这是我的代码: private byte[] getFileByteArray(File file) { try { RandomAccessFile raf = new RandomAccessFile(file,"r"); FileChannel channel = raf.

我在 Windows中使用java删除文件有一些问题.由于某种原因,java正在锁定我的文件,我不知道为什么.这是我的代码:

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,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,ex);
    }
    return null;
}

file.delete()以及在资源管理器中手动尝试拒绝删除文件,因为它仍在使用中.在Linux中似乎都很好.

我错过了()somehwhere吗?我可以确认首先使文件的方法是关闭文件,因为我可以使用file.delete()运行上述代码之前删除该文件,

额外信息:上面的代码是一个名为getFileByteArray(File file)的方法的一部分,正在被调用:

public byte[] createReport(int id) {

    Report report = new Report();
    String filename = report.CreateReport(id);
    return getFileByteArray(new File(filename));
}

谢谢

更新:我设法通过使用ByteArrayOutputStream读取千字节千字节到字节数组中来解决这个问题

作为下面提到的海报,Java中有一个已知的错误,因为Windows有文件映射问题.

这是一个已知的Java在Windows上的Bug,请参阅 Bug #4715154

Sun评估了这个问题,并通过以下解释来关闭了这个bug:

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.

(编辑:常州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读