检查文件是否已经打开
问题描述:
我需要编写一个自定义的批处理文件重命名器.我已经完成了大部分工作,只是我不知道如何检查文件是否已经打开.我只是在使用 java.io.File
包,并且有一个 canWrite()
方法,但这似乎没有测试文件是否被另一个人使用程序.关于如何完成这项工作的任何想法?
I need to write a custom batch File renamer. I've got the bulk of it done except I can't figure out how to check if a file is already open. I'm just using the java.io.File
package and there is a canWrite()
method but that doesn't seem to test if the file is in use by another program. Any ideas on how I can make this work?
答
使用 Apache Commons IO 库...
Using the Apache Commons IO library...
boolean isFileUnlocked = false;
try {
org.apache.commons.io.FileUtils.touch(yourFile);
isFileUnlocked = true;
} catch (IOException e) {
isFileUnlocked = false;
}
if(isFileUnlocked){
// Do stuff you need to do with a file that is NOT locked.
} else {
// Do stuff you need to do with a file that IS locked
}