【发布时间】:2018-12-09 19:56:19
【问题描述】:
我有一个函数,它必须将键值对放入存储在文件中的映射中。如果文件不存在,我必须创建它。当我使用 Filelock lock() 处理文件时,我尝试锁定文件。但是当我尝试写入它时(在锁定部分的内部),我得到 IO 异常: 抑制:java.io.IOException:该进程无法访问该文件,因为另一个进程已锁定文件的一部分 我可能不会正确使用 lock() 。这是我的功能:
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;
【问题讨论】:
-
很高兴听到有关创建文件/使用锁定打开现有文件的任何其他解决方案,以使写入操作线程安全。
-
抛出什么
IOException?
标签: java multithreading nio filechannel filelock