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

前端 未结 5 702
抹茶落季
抹茶落季 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:39

    This one should also work for Windows systems. But attention, does not work for Linux!

         private boolean isFileClosed(File file) {  
                boolean closed;
                Channel channel = null;
                try {
                    channel = new RandomAccessFile(file, "rw").getChannel();
                    closed = true;
                } catch(Exception ex) {
                    closed = false;
                } finally {
                    if(channel!=null) {
                        try {
                            channel.close();
                        } catch (IOException ex) {
                            // exception handling
                        }
                    }
                }
                return closed;
        }
    

提交回复
热议问题