How to check if a file is open by another process (Java/Linux)?

前端 未结 5 745
抹茶落季
抹茶落季 2020-12-08 14:30

I am trying to check if a certain java.io.File is open by an external program. On windows I use this simple trick:

try {
    FileOutputStream fos = new FileO         


        
5条回答
  •  广开言路
    2020-12-08 14:35

    Thanks for the original suggestion. I have one small upgrade that is somewhat important to that method:

    FileOutputStream fos = null;
    try {
        // Make sure that the output stream is in Append mode. Otherwise you will
        // truncate your file, which probably isn't what you want to do :-) 
        fos = new FileOutputStream(file, true);
        // -> file was closed
    } catch(IOException e) {
        // -> file still open
    } finally {
        if(fos != null) {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    Cheers, Gumbatron

提交回复
热议问题