yangys
8 天以前 f4c6e0e1308bccb943ca1cddfdf7f643b6b6a1aa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package org.springblade.mdm.machineback.filewatch;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Files;
import java.nio.file.Path;
/*
监控文件是否传输完成(使用可否锁定来判断)
 */
 
public class FileLockChecker {
    public static boolean isFileCompletelyWritten(Path file) {
        try (RandomAccessFile raf = new RandomAccessFile(file.toFile(), "rw");
             FileChannel channel = raf.getChannel()) {
 
            // 尝试获取独占锁
            FileLock lock = channel.tryLock();
            if (lock != null) {
                lock.release();
                // 如果能获取锁,说明文件不再被写入
                return true;
            }
            return false;
        } catch (Exception e) {
            // 如果发生异常,可能文件仍在被写入
            return false;
        }
    }
 
    /**
     * 文件是否传输完成(采用前后文件大小比对方法)
     * @param file
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    public static boolean isFileComplete(Path file) throws IOException, InterruptedException {
        long initialSize = Files.size(file);
        Thread.sleep(3000); // 等待1秒
        long currentSize = Files.size(file);
        return initialSize == currentSize;
    }
}