首页>代码>java开发实现监控某个文件目录并且实时同步文件到目标文件目录和ftp服务器的工具类>/src/main/java/com/zuidaima/util/FileAlterationListener.java
package com.zuidaima.util; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import org.apache.commons.io.monitor.FileAlterationListenerAdaptor; import cn.hutool.core.util.CharUtil; import cn.hutool.log.StaticLog; /** * 文件监控服务 */ public class FileAlterationListener extends FileAlterationListenerAdaptor { @SuppressWarnings("unchecked") public static void watchService(String dir) { final Path path = Paths.get(dir); boolean isUpload = PropsUtil.getBooleanValByProps(PropsUtil.IS_UPLOAD); boolean isCopy = PropsUtil.getBooleanValByProps(PropsUtil.IS_OPEN_COPY); Integer second = PropsUtil.getIntegerValByProps(PropsUtil.SECOND); try (WatchService watchService = FileSystems.getDefault().newWatchService()) { path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); StaticLog.info("启动成功!"); while (true) { final WatchKey key = watchService.take(); for (WatchEvent<?> watchEvent : key.pollEvents()) { final WatchEvent.Kind<?> kind = watchEvent.kind(); final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent; final Path fileName = watchEventPath.context(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } // 创建事件 if (kind == StandardWatchEventKinds.ENTRY_CREATE) { // 将文件复制到目标文件夹 if (isCopy) { Thread.sleep(second * 1000); String[] dirs = ((String) PropsUtil.props.get(PropsUtil.NEW_DIRS)) .split(CharUtil.BACKSLASH + PropsUtil.verticalLine); for (String root : dirs) { CopyFile.copyFile(dir + CharUtil.BACKSLASH + fileName, root + CharUtil.BACKSLASH + fileName); StaticLog.info("复制到{}成功", root); } } // 上传文件到ftp if (isUpload) { String[] urls = ((String) PropsUtil.props.get(PropsUtil.FTP_HOST)) .split(CharUtil.BACKSLASH + PropsUtil.verticalLine); String strFileName = dir + CharUtil.BACKSLASH + fileName; for (String url : urls) { FtpUtil.uploadFile(url, strFileName); } } } } if (!key.reset()) { break; } } } catch (IOException | InterruptedException ex) { ex.printStackTrace(); } } }
最近下载更多