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