Check if file is already open

前端 未结 8 1273
悲&欢浪女
悲&欢浪女 2020-11-22 14:32

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.

8条回答
  •  渐次进展
    2020-11-22 14:56

    Hi I really hope this helps.

    I tried all the options before and none really work on Windows. The only think that helped me accomplish this was trying to move the file. Event to the same place under an ATOMIC_MOVE. If the file is being written by another program or Java thread, this definitely will produce an Exception.

     try{
    
          Files.move(Paths.get(currentFile.getPath()), 
                   Paths.get(currentFile.getPath()), StandardCopyOption.ATOMIC_MOVE);
    
          // DO YOUR STUFF HERE SINCE IT IS NOT BEING WRITTEN BY ANOTHER PROGRAM
    
     } catch (Exception e){
    
          // DO NOT WRITE THEN SINCE THE FILE IS BEING WRITTEN BY ANOTHER PROGRAM
    
     }
    

提交回复
热议问题