思想:
文件打开时,给它建立一个临时文件,其他操作要打开这个文件,先检测临时文件在不,在的话就DENY掉.。
实现:
private void checkFile(File file, long beginTime, int timeOut) throws InterruptedException, IOException {
while (true) {
//check file, is modified?
if (file.lastModified() > beginTime) {
System.out.println("modified...");
File temp = new File(file.getParent() + "//~" + file.getName());
while (true) {
//check the file is released?
if (file.renameTo(temp)) {
//recover the file
temp.renameTo(file);
break;
}
else {
System.out.println("waiting for release");
Thread.sleep(timeOut);
}
}
break;
}
else {
System.out.println("waiting...");
Thread.sleep(timeOut);
}
}
}
先用lastModified判断文件是否被修改.
再判断文件是否被释放(不再被占用),用renameTo判断。
调用:
File file = new File(FILE_NAME);
//get the last modified time
long beginTime = file.lastModified();
//start excel
Runtime.getRuntime().exec("cmd /c start " + FILE_NAME);
this.checkFile(file, beginTime, 500);
标签: