Home » Core Java » apache » commons » io » monitor » FileAlterationMonitor » org.apache.commons.io.monitor.FileAlterationMonitor Example

About Ashraf Sarhan

Ashraf Sarhan
Ashraf Sarhan is a passionate software engineer, an open source enthusiast, has a Bsc. degree in Computer and Information Systems from Alexandria University. He is experienced in building large, scalable and distributed enterprise applications/service in multiple domains. He also has a keen interest in JavaEE, SOA, Agile and Big Data technologies.

org.apache.commons.io.monitor.FileAlterationMonitor Example

In this example we shall show you how to make use of FileAlterationMonitor class, FileAlterationMonitor comes from the FileMonitor API of the Commons IO library which provided by the Apache Foundation. It spawns a monitoring thread triggering any registered FileAlterationObserver at a specified interval. A FileAlterationObserver represents the state of files below a root directory, checking the filesystem and notifying FileAlterationListener of create, change or delete events.

 

 

1. How we can use it?

As we can notice, there are another two players (FileAlterationListener, FileAlterationObserver) in the FileMonitor which support FileAlterationMonitor. So, the typical usage of the FileMonitor follows the below steps:

  1. Create FileAlterationListener implementation(s) that process the file/directory create, change and delete events.
  2. Register the listener(s) with a FileAlterationObserver for the appropriate directory.
  3. Register the observer(s) with a FileAlterationMonitor.
  4. Run the FileAlterationMonitor.

2. Where we can use it?

  1. J2EE application servers like Tomcat and others have a auto load feature where in as soon as deployment descriptor changes or servlet class changes the application restarts. Although, they may use other libraries but we can make the same solution using the FileMonitor.
  2. Also, we can make a dynamic loading configuration file where some configuration files modifications need to restart your application, it is very troubling and very helpless, who told him only loaded once. So, we can trigger the configuration file to be reloaded automatically when changes occur using the FileMonitor.

3. Dependency:

Commons IO 2.4 is the latest version and requires a minimum of JDK 1.6 – Download now! OR we can use the following maven dependency in our POM.

<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.4</version>
</dependency>

4. Example:

The FileAlterationListenerImpl.java class is an implementation of FileAlterationListener which will be our worker to process the file/directory create, change and delete events. We just need to override its inherited methods from FileAlterationListener to do our own logic.

FileAlterationListenerImpl.java:

package com.jcg;

import java.io.File;
import java.util.Date;

import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationObserver;

/**
 * @author ashraf
 *
 */
public class FileAlterationListenerImpl implements FileAlterationListener {

	@Override
	public void onStart(final FileAlterationObserver observer) {
		System.out.println("The FileListener has started on "
				+ observer.getDirectory().getAbsolutePath());
	}

	@Override
	public void onDirectoryCreate(final File directory) {
		System.out.println(directory.getAbsolutePath() + " was created.");
	}

	@Override
	public void onDirectoryChange(final File directory) {
		System.out.println(directory.getAbsolutePath() + " wa modified");
	}

	@Override
	public void onDirectoryDelete(final File directory) {
		System.out.println(directory.getAbsolutePath() + " was deleted.");
	}

	@Override
	public void onFileCreate(final File file) {
		System.out.println(file.getAbsoluteFile() + " was created.");
		System.out.println("1. length: " + file.length());
		System.out
				.println("2. last modified: " + new Date(file.lastModified()));
		System.out.println("3. readable: " + file.canRead());
		System.out.println("4. writable: " + file.canWrite());
		System.out.println("5. executable: " + file.canExecute());
	}

	@Override
	public void onFileChange(final File file) {
		System.out.println(file.getAbsoluteFile() + " was modified.");
		System.out.println("1. length: " + file.length());
		System.out
				.println("2. last modified: " + new Date(file.lastModified()));
		System.out.println("3. readable: " + file.canRead());
		System.out.println("4. writable: " + file.canWrite());
		System.out.println("5. executable: " + file.canExecute());
	}

	@Override
	public void onFileDelete(final File file) {
		System.out.println(file.getAbsoluteFile() + " was deleted.");
	}

	@Override
	public void onStop(final FileAlterationObserver observer) {
		System.out.println("The FileListener has stopped on "
				+ observer.getDirectory().getAbsolutePath());
	}

}

The FileMonitorDemo.java class creates a new FileAlterationObserver for the user home directory and register a new FileAlterationListenerImpl listener, then we register our observer(s) with a a new FileAlterationMonitor, which creates a new thread, invoking the observer at the predefined time interval (i.e., every 30 seconds).

FileMonitorDemo.java:

package com.jcg;

import java.io.File;

import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

/**
 * @author ashraf
 *
 */
public class FileMonitorDemo {

	// Get the user home directory to be monitored
	private static final String FOLDER = System.getProperty("user.home");

	// The monitor will perform polling on the folder every 30 seconds
	private static final long pollingInterval = 30 * 1000;

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {

		// Change this to match the environment you want to watch.
		final File directory = new File(FOLDER);

		// Create a new FileAlterationObserver on the given directory
		FileAlterationObserver fao = new FileAlterationObserver(directory);

		// Create a new FileAlterationListenerImpl and pass it the previously created FileAlterationObserver
		fao.addListener(new FileAlterationListenerImpl());

		// Create a new FileAlterationMonitor with the given pollingInterval period
		final FileAlterationMonitor monitor = new FileAlterationMonitor(
				pollingInterval);

		// Add the previously created FileAlterationObserver to FileAlterationMonitor
		monitor.addObserver(fao);

		// Start the FileAlterationMonitor
		monitor.start();

		System.out.println("Starting monitor (" + FOLDER
				+ "). \"Press CTRL+C to stop\"");
	}

}

We can notice that when we create a new file ashraf in the monitored directory, our FileAlterationMonitor feels this change and prints the file properties to the console.
Output:

Starting monitor (/home/ashraf). "Press CTRL+C to stop"
The FileListener has started on /home/ashraf
The FileListener has stopped on /home/ashraf
The FileListener has started on /home/ashraf
/home/ashraf/ashraf was created.
1. length: 0
2. last modified: Sun Dec 07 22:15:14 EET 2014
3. readable: true
4. writable: true
5. executable: false
The FileListener has stopped on /home/ashraf

4. Download the Source Code of this Example:

This was an example of Commons IO FileAlterationMonitor class.

Download
You can download the full source code of this example here: FileAlterationMonitorExampleCode.zip
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of