Java: opening and reading from a file without locking it

前端 未结 4 782
盖世英雄少女心
盖世英雄少女心 2020-12-16 17:42

I need to be able to mimic \'tail -f\' with Java. I\'m trying to read a log file as it\'s being written by another process, but when I open the file to read it, it locks the

4条回答
  •  伪装坚强ぢ
    2020-12-16 18:34

    Windows uses mandatory locking for files unless you specify the right share flags while you open. If you want to open a busy file, you need to Win32-API CreateFile a handle with the sharing flags FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE.

    This is used inside the JDK in a few places to open files for reading attributes and stuff, but as far as I can see it is not exported/available to Java Class Library level. So you would need to find a native library to do that.

    I think as a quick work around you can read process.getInputStream() from the command "cmd /D/C type file.lck"

提交回复
热议问题