bot*_*bot 5 java nio filelock delete-file
我在本地文件系统上有一堆文件.我的服务器将提供这些文件.在某些情况下,服务器将收到删除文件的指令.目前我正在使用FileChannel.lock()锁定文件,这主要是为了确保在我尝试删除文件时其他一些进程没有编辑该文件.
如果我成功获取了锁,我可以立即删除该文件,还是需要先释放锁?
像这样:
FileOutputStream out = new FileOutputStream(file);
FileChannel channel = out.getChannel();
FileLock lock = channel.lock();
if(lock.isValid() && !lock.isShared()){
Path filePath = Paths.get(file.getPath());
Files.delete(filePath);
}
Run Code Online (Sandbox Code Playgroud)
我删除文件后是否需要释放锁定?
或者应该是这样(lock.release()添加):
FileOutputStream out = new FileOutputStream(file);
FileChannel channel = out.getChannel();
FileLock lock = channel.lock();
if(lock.isValid() && !lock.isShared()){
lock.release();
Path filePath = Paths.get(file.getPath());
Files.delete(filePath);
}
Run Code Online (Sandbox Code Playgroud)
编辑:
所以事实证明上面的代码无论如何都不会工作,因为你不能用a修改文件FileInputStream,当然,它只是只读.我已修改上面的代码FileOutputStream而不是使用它,但它仍然不能正常工作,因为即使我从通道释放锁,该file对象仍然有一个锁.所以我像这样修改了代码:
FileOutputStream out = new FileOutputStream(file);
FileChannel channel = out.getChannel();
FileLock lock = channel.lock();
if(lock.isValid() && !lock.isShared()){
channel.close();
boolean deleted = file.delete();
logger.info("{} @{} File {} deleted: {}", id, type, file.getName(), deleted);
}
Run Code Online (Sandbox Code Playgroud)
这似乎按预期工作.我还是想知道这是否安全,或者是否有更好的方法来做到这一点?
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |