How to test if a file is “complete” (completely written) with Java

后端 未结 10 1622
再見小時候
再見小時候 2020-12-05 04:21

Let\'s say you had an external process writing files to some directory, and you had a separate process periodically trying to read files from this directory. The problem to

10条回答
  •  再見小時候
    2020-12-05 05:18

    I had no option of using temp markers etc as the files are being uploaded by clients over keypair SFTP. they can be very large in size.

    Its quite hacky but I compare file size before and after sleeping a few seconds.

    Its obviously not ideal to lock the thread but in our case it is merely running as a background system processes so seems to work fine

    private boolean isCompletelyWritten(File file) throws InterruptedException{
        Long fileSizeBefore = file.length();
        Thread.sleep(3000);
        Long fileSizeAfter = file.length();
    
        System.out.println("comparing file size " + fileSizeBefore + " with " + fileSizeAfter);
    
        if (fileSizeBefore.equals(fileSizeAfter)) {
            return true;
        }
        return false;
    }
    

    Note: as mentioned below this might not work on windows. This was used in a Linux environment.

提交回复
热议问题