watchService.take()太慢了,用以下面的文件更新时间做对比,直接判断更快
package com.tools.fb.tools.redfine; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import com.aliyun.oss.model.PutObjectResult; /** * @author zhenyuan.he */ public class WatchFileChangedTask { static final String BUCKET_NAME = "kaola-class"; static final String REDEFINE_DIR = "redefine/"; final static String FILE_PATH = "/Users/hezhenyuan/Desktop/coding/klad-searchad-compose"; private static final String FILE_TYPE = ".class"; private static final List<String> EXCLUDE_PATHS = new ArrayList<>(); private static final Map<String, String> FILE_PATHS = new HashMap<>(); static { EXCLUDE_PATHS.add("target/test-classes"); } /** * 读取目录下的所有文件 * * @param dir 目录 * @param fileType 文件类型 * @param fileNames 保存文件名的集合 */ public static void findContainsFileDir(File dir, String fileType, List<String> excludePaths, Map<String, Long> fileNames) { // 判断是否存在目录 if (dir == null || !dir.exists() || !dir.isDirectory()) { return; } // 读取目录下的所有目录文件信息 String[] files = dir.list(); assert files != null; Arrays.stream(files).forEach( f -> { File file = new File(dir, f); // 如果文件 if (file.isFile() && file.getName().endsWith(fileType)) { FILE_PATHS.put(file.getName(), file.getPath()); final String path = dir.getPath(); String exclude = excludePaths.stream().filter(path::contains).findFirst().orElse(null); if (exclude != null && !exclude.isEmpty()) { return; } if (!fileNames.containsKey(path)) { fileNames.put(file.getName(), file.lastModified()); } } else { findContainsFileDir(file, fileType, excludePaths, fileNames); } } ); } /** * 模拟测试 */ public static void main(String[] args) { try { File file = new File(FILE_PATH); Map<String, Long> odlFileNames = new HashMap<>(10000); findContainsFileDir(file, FILE_TYPE, EXCLUDE_PATHS, odlFileNames); while (true) { Map<String, Long> newFileNames = new HashMap<>(); findContainsFileDir(file, FILE_TYPE, EXCLUDE_PATHS, newFileNames); for (String fileName : newFileNames.keySet()) { if (newFileNames.get(fileName).longValue() != odlFileNames.get(fileName)) { final String filePath = FILE_PATHS.get(fileName); System.err.println("文件:" + fileName); OssManager.upload(BUCKET_NAME, REDEFINE_DIR + fileName, filePath); } } odlFileNames.putAll(newFileNames); Thread.sleep(1000); } } catch (Throwable e) { System.err.println(e.getMessage()); } } }