我试图检查某个java.io.File是否由外部程序打开.在Windows上我使用这个简单的技巧:
try {
FileOutputStream fos = new FileOutputStream(file);
// -> file was closed
} catch(IOException e) {
// -> file still open
}
Run Code Online (Sandbox Code Playgroud)
我知道基于unix的系统允许在多个进程中打开文件...是否有类似的技巧可以为基于unix的系统实现相同的结果?
任何帮助/黑客高度赞赏:-)
Han*_*ein 10
以下是如何将lsof用于基于unix的系统的示例:
public static boolean isFileClosed(File file) {
try {
Process plsof = new ProcessBuilder(new String[]{"lsof", "|", "grep", file.getAbsolutePath()}).start();
BufferedReader reader = new BufferedReader(new InputStreamReader(plsof.getInputStream()));
String line;
while((line=reader.readLine())!=null) {
if(line.contains(file.getAbsolutePath())) {
reader.close();
plsof.destroy();
return false;
}
}
} catch(Exception ex) {
// TODO: handle exception ...
}
reader.close();
plsof.destroy();
return true;
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
这个也应该适用于 Windows 系统。但注意,不适用于Linux!
private boolean isFileClosed(File file) {
boolean closed;
Channel channel = null;
try {
channel = new RandomAccessFile(file, "rw").getChannel();
closed = true;
} catch(Exception ex) {
closed = false;
} finally {
if(channel!=null) {
try {
channel.close();
} catch (IOException ex) {
// exception handling
}
}
}
return closed;
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试@ZZ Coder 的文件锁信号量类型代码
File file = new File(fileName);
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
FileLock lock = channel.lock();
try {
lock = channel.tryLock();
// Ok. You get the lock
} catch (OverlappingFileLockException e) {
// File is open by someone else
} finally {
lock.release();
}
Run Code Online (Sandbox Code Playgroud)