Check if file is already open

前端 未结 8 1195
悲&欢浪女
悲&欢浪女 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 15:13

    (The Q&A is about how to deal with Windows "open file" locks ... not how implement this kind of locking portably.)

    This whole issue is fraught with portability issues and race conditions:

    • You could try to use FileLock, but it is not necessarily supported for your OS and/or filesystem.
    • It appears that on Windows you may be unable to use FileLock if another application has opened the file in a particular way.
    • Even if you did manage to use FileLock or something else, you've still got the problem that something may come in and open the file between you testing the file and doing the rename.

    A simpler though non-portable solution is to just try the rename (or whatever it is you are trying to do) and diagnose the return value and / or any Java exceptions that arise due to opened files.

    Notes:

    1. If you use the Files API instead of the File API you will get more information in the event of a failure.

    2. On systems (e.g. Linux) where you are allowed to rename a locked or open file, you won't get any failure result or exceptions. The operation will just succeed. However, on such systems you generally don't need to worry if a file is already open, since the OS doesn't lock files on open.

    0 讨论(0)
  • 2020-11-22 15:13

    I don't think you'll ever get a definitive solution for this, the operating system isn't necessarily going to tell you if the file is open or not.

    You might get some mileage out of java.nio.channels.FileLock, although the javadoc is loaded with caveats.

    0 讨论(0)
提交回复
热议问题