我有一个函数,它必须将键值对放入文件中的映射中。如果文件不存在,我必须创建它。当我使用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;发布于 2018-07-01 16:13:37
打开文件两次--一次通过FileChannel,另一次通过FileOutputStream。然后通过FileChannel锁定文件,但尝试通过FileOutputStream写入文件。这就是为什么流被通道的锁阻塞的原因。
FileChannel有自己的读/写方法。使用通道或流,但不能同时使用。
编辑文件锁是为了防止另一个进程写入文件,因此,除非您知道可能有其他进程试图写入文件,否则通常不需要在写入文件之前显式锁定文件。
https://stackoverflow.com/questions/51121759
复制相似问题