首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ObjectInputStream在filelock锁部分抛出ioexception

ObjectInputStream在filelock锁部分抛出ioexception
EN

Stack Overflow用户
提问于 2018-07-01 08:47:17
回答 1查看 263关注 0票数 0

我有一个函数,它必须将键值对放入文件中的映射中。如果文件不存在,我必须创建它。当我使用Filelock lock()时,我试图锁定该文件。但是,当我试图写入它(在锁定部分中)时,我得到IO异常: java.io.IOException:进程无法访问该文件,因为另一个进程锁定了文件的一部分,我可能没有正确地使用lock()。这是我的功能:

代码语言:javascript
复制
        private void createDataSet(String key, String data) throws IOException, ClassNotFoundException{

                final   String path = (fileName);
    //            1. Check if file exists
    //            2. If file exists, write/override key/value.
                Path nPath = Paths.get(path);
                HashMap<String, List<String>> map = new HashMap<String, List<String>>();
    //            createFile is atomic, no need to check if exists.
                    try(FileChannel fileChannel = FileChannel.open(nPath,StandardOpenOption.WRITE,StandardOpenOption.APPEND
                            , StandardOpenOption.CREATE);
                        FileOutputStream fos= new FileOutputStream(path, false);
                        ObjectOutputStream oos= new ObjectOutputStream(fos);

                        ){
                        FileLock lock = fileChannel.lock();
                        if(fileChannel.size()==4){
                            map.put(key, values);
                            oos.writeObject(map);
                        }else{
                            ObjectInputStream objectIn = new ObjectInputStream(Channels.newInputStream(fileChannel));
                            Object obj = objectIn.readObject();
                            map = (HashMap<String, List<String>>) obj;
                            map.put(key, values);
// In this row exception being throwed:
                            oos.writeObject(map); 
                        }
                        oos.close();
                        fos.close();
                        lock.release();
                    }
                    return;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-01 16:13:37

打开文件两次--一次通过FileChannel,另一次通过FileOutputStream。然后通过FileChannel锁定文件,但尝试通过FileOutputStream写入文件。这就是为什么流被通道的锁阻塞的原因。

FileChannel有自己的读/写方法。使用通道或流,但不能同时使用。

编辑文件锁是为了防止另一个进程写入文件,因此,除非您知道可能有其他进程试图写入文件,否则通常不需要在写入文件之前显式锁定文件。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51121759

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档