Java检查文件是否可写(被占用)的一个技巧

思想:

文件打开时,给它建立一个临时文件,其他操作要打开这个文件,先检测临时文件在不,在的话就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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值