我是楼主
因为会在
while(true) {
  doCheck();
  sleep(500);
}
进行检查,如果抛异常的话,会比较慢.

解决方案 »

  1.   

    你所指的被占用是指人为地打开了这个excel是吧?
    那我就不知道了
      

  2.   

    文件打开时,给它建立一个临时文件,其他操作要打开这个文件,先检测临时文件在不,在的话就DENY掉.
      

  3.   

    文件打开,不是由程序打开的,是excel打开的.
      

  4.   

    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);