java中怎样判断一个文件是否被打开?
我想判断一个File是否被打开,网上有些人说canWrite()可以,但是我用canWrite()测试好像并不好用。程序如下:
public class TestFileWriter {
public static void main(String[] args) {
File file = new File("D:\\a.xls");
System.out.println(file.exists());
System.out.println(file.canWrite()); //无论文件是否打开,都输出true
}
public class TestFileWriter {
public static void main(String[] args) {
File file = new File("D:\\a.xls");
System.out.println(file.renameTo(file));
}
public static void checkFile() throws Exception {
FileOutputStream fis = new FileOutputStream(new File("e:\\mm.bmp"));
FileChannel fc = fis.getChannel();
FileLock lock = fc.tryLock();
if(lock == null){
System.out.println("已被打开");
}else{
System.out.println("获取对此通道的文件的独占锁定。");
try {
Thread.sleep(new Random().nextInt(100000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}