Java Lightweight file Monitoring

Source: Internet
Author: User
Tags create directory

Introduced

This article mainly introduces a kind of lightweight file monitoring method, the file Create & change & Delete, there is a corresponding event method for processing. For the core file monitor class, we inherited a listener adapter class Filealterationlisteneradaptor, which makes it easier to rewrite every event method.


File Generator Class

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 S Tatic final Logger LOG = Logger.getlogger (filegenerator.class);p rivate String directory = null;private static Date date = New Date ();p ublic filegenerator (String directory) {this.directory = directory;} private void Generator (string directory) {for (int i = 0; i <; i++) {String fileName = Commontooler.getdatetimeforma T (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 ();}}} @Overridepublic void Run () {this.generator (directory);}}

File Monitor Class

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  );p rivate static filemonitor filemonitor;private static int pagenumber = 0;private FileMonitor () {}//Get Singleton object Instancepublic static FileMonitor Getfilemonitor () {if (FileMonitor = = null) {synchronized (Filemonitor.class) {if (Filem Onitor = = null) {FileMonitor = new FileMonitor ();}}} return filemonitor;} Create file event@overridepublic 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 (pageNumb ER) + ". xml"), try {fileutils.movefile (file, destfile),} catch (IOException IoE) {ioe.printstacktrace ();} pagenumber++;} Change file event@overridepublic void onfilechange (file file) {log.info ("[Change]:" + file.getabsolutepath ());} Delete file event@overridepublic void onfiledelete (file file) {log.info ("[Delete]:" + file.getabsolutepath ());} public void Monitor (String directory, int. interval) {//Observer file whose suffix is pm filealterationobserver filealtera Tionobserver = new Filealterationobserver (directory, Filefilterutils.and (Filefilterutils.filefilefilter (), Filefilterutils.suffixfilefilter (". PM")), null);//ADD listener for EVent (File Create & change & Delete) Filealterationobserver.addlistener (this);//Monitor per Intervalfilealterationmonitor filealterationmonitor = new Filealterationmonitor (interval, filealterationobserver); try {//Start to Monitorfilealterationmonitor.start ();} catch (Exception e) {e.printstacktrace ()}}}

File Tester Class

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);p rivate static String directory = "/home/omc/tmp";p ublic 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 millisecondsfilemonitor.getfilemonitor (). Monitor ( directory, 500); Log.info ("File generater ...");//New runnable instancefilegenerator filegeneratorrunnable = new Filegenerator ( directory)//Start to Multi-thread for generating filefor (int i = 0; i <; i++) {Thread filegeneratorthread = new T Hread (filegeneratorrunnable); filegeneratorthread. Start ();}}} 


Common Tool Class

Package Shuai.study.file.tooler;import java.text.simpledateformat;import java.util.date;/** * @author Shengshu *  */public class Commontooler {//Date time formatpublic static String Getdatetimeformat (date date) {SimpleDateFormat simple DateFormat = new SimpleDateFormat ("yyyymmdd-hhmm"); String datetime = Simpledateformat.format (date); return datetime;} Page formatpublic static string pagingformat (int pagenumber) {String pagenumberstr = "P00"; if (PageNumber < 0) {thro W New NumberFormatException ("the page number should not be negative");} if (PageNumber <) {Pagenumberstr = String.Format ("p0%d", pagenumber);} else {pagenumberstr = String.Format ("P%d", PA Genumber);} return pagenumberstr;}}

Java Lightweight file monitoring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.