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

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

    Use this for Unix if you are transferring files using FTP or Winscp:

    public static void isFileReady(File entry) throws Exception {
            long realFileSize = entry.length();
            long currentFileSize = 0;
            do {
                try (FileInputStream fis = new FileInputStream(entry);) {
                    currentFileSize = 0;
                    while (fis.available() > 0) {
                        byte[] b = new byte[1024];
                        int nResult = fis.read(b);
                        currentFileSize += nResult;
                        if (nResult == -1)
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("currentFileSize=" + currentFileSize + ", realFileSize=" + realFileSize);
            } while (currentFileSize != realFileSize);
        }
    

提交回复
热议问题