原文地址:http://blog.csdn.net/three_man/article/details/31012903?utm_source=tuicool
介绍
本文主要介绍一种轻量级的文件监控方式,对文件的Create & Change & Delete,都有一个对应的Event方法来进行处理。对于核心的File Monitor Class,我们继承一个监听适配器类FileAlterationListenerAdaptor,这样会更方便,就不用再去重写每个Event方法。
package shuai.study.file.generator; import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date; import org.apache.log4j.Logger; import shuai.study.file.tooler.CommonTooler; /**
* @author shengshu
*
*/
public class FileGenerator implements Runnable {
private static final Logger LOG = Logger.getLogger(FileGenerator.class); private String directory = null; private static Date date = new Date(); public FileGenerator(String directory) {
this.directory = directory;
} private void generator(String directory) {
for (int i = 0; i < 10; i++) {
String fileName = CommonTooler.getDateTimeFormat(date) + "-" + Thread.currentThread().getId() + i + ".pm"; LOG.info("[Path]: " + directory + "/" + fileName); try {
// Create file (path: directory/fileName)
Files.createFile(Paths.get(directory, fileName));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
} @Override
public void run() {
this.generator(directory);
}
}
package shuai.study.file.monitor; import java.io.File;
import java.io.IOException; import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.apache.log4j.Logger; import shuai.study.file.tooler.CommonTooler; /**
* @author shengshu
*
*/
public class FileMonitor extends FileAlterationListenerAdaptor {
private static final Logger LOG = Logger.getLogger(FileMonitor.class); private static FileMonitor fileMonitor; private static int pageNumber = 0; private FileMonitor() { } // Get singleton object instance
public static FileMonitor getFileMonitor() {
if (fileMonitor == null) {
synchronized (FileMonitor.class) {
if (fileMonitor == null) {
fileMonitor = new FileMonitor();
}
}
} return fileMonitor;
} // Create file event
@Override
public void onFileCreate(File file) {
LOG.info("[Create]: " + file.getAbsolutePath()); String fileAbsolutePath = file.getAbsolutePath();
String fileAbsoluteParentPath = file.getParent();
String fileBaseName = FilenameUtils.getBaseName(fileAbsolutePath); File destFile = new File(fileAbsoluteParentPath + File.separator + fileBaseName + "-" + CommonTooler.pagingFormat(pageNumber) + ".xml"); try {
FileUtils.moveFile(file, destFile);
} catch (IOException ioe) {
ioe.printStackTrace();
} pageNumber++;
} // Change file event
@Override
public void onFileChange(File file) {
LOG.info("[Change]: " + file.getAbsolutePath());
} // Delete file event
@Override
public void onFileDelete(File file) {
LOG.info("[Delete]: " + file.getAbsolutePath());
} public void monitor(String directory, int interval) {
// Observer file whose suffix is pm
FileAlterationObserver fileAlterationObserver = new FileAlterationObserver(directory, FileFilterUtils.and(FileFilterUtils.fileFileFilter(),
FileFilterUtils.suffixFileFilter(".pm")), null); // Add listener for event (file create & change & delete)
fileAlterationObserver.addListener(this); // Monitor per interval
FileAlterationMonitor fileAlterationMonitor = new FileAlterationMonitor(interval, fileAlterationObserver); try {
// Start to monitor
fileAlterationMonitor.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package shuai.study.file.tester; import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths; import org.apache.log4j.Logger; import shuai.study.file.generator.FileGenerator;
import shuai.study.file.monitor.FileMonitor; /**
* @author shengshu
*
*/
public class FileTester {
private static final Logger LOG = Logger.getLogger(FileTester.class); private static String directory = "/home/omc/tmp"; public static void main(String[] args) {
// Create directory if it does not exist
try {
Files.createDirectory(Paths.get(directory));
} catch (IOException ioe) {
ioe.printStackTrace();
} LOG.info("File Monitor...");
// Start to monitor file event per 500 milliseconds
FileMonitor.getFileMonitor().monitor(directory, 500); LOG.info("File Generater...");
// New runnable instance
FileGenerator fileGeneratorRunnable = new FileGenerator(directory); // Start to multi-thread for generating file
for (int i = 0; i < 10; i++) {
Thread fileGeneratorThread = new Thread(fileGeneratorRunnable);
fileGeneratorThread.start();
}
} }
package shuai.study.file.tooler; import java.text.SimpleDateFormat;
import java.util.Date; /**
* @author shengshu
*
*/
public class CommonTooler { // Date time format
public static String getDateTimeFormat(Date date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd-HHmm");
String dateTime = simpleDateFormat.format(date); return dateTime;
} // Page format
public static String pagingFormat(int pageNumber) {
String pageNumberStr = "P00"; if (pageNumber < 0) {
throw new NumberFormatException("The page number should not be negative");
} if (pageNumber < 10) {
pageNumberStr = String.format("P0%d", pageNumber);
} else {
pageNumberStr = String.format("P%d", pageNumber);
} return pageNumberStr;
} }