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

后端 未结 10 1621
再見小時候
再見小時候 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:04

    One more method to test that a file is completely written:

    private void waitUntilIsReadable(File file) throws InterruptedException {
        boolean isReadable = false;
        int loopsNumber = 1;
        while (!isReadable && loopsNumber <= MAX_NUM_OF_WAITING_60) {
            try (InputStream in = new BufferedInputStream(new FileInputStream(file))) {
                log.trace("InputStream readable. Available: {}. File: '{}'",
                        in.available(), file.getAbsolutePath());
                isReadable = true;
            } catch (Exception e) {
                log.trace("InputStream is not readable yet. File: '{}'", file.getAbsolutePath());
                loopsNumber++;
                TimeUnit.MILLISECONDS.sleep(1000);
            }
        }
    }
    

提交回复
热议问题