How can I lock a file using java (if possible)

前端 未结 8 1195
无人及你
无人及你 2020-11-21 23:48

I have a Java process that opens a file using a FileReader. How can I prevent another (Java) process from opening this file, or at least notify that second process that the

8条回答
  •  攒了一身酷
    2020-11-22 00:43

    Use this for unix if you are transferring using winscp or ftp:

    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);
        }
    

提交回复
热议问题