How to monitor file changes using java.nio JDK 7 API (WatcherService example)


If you want to monitor files under a directory, you can use the following source code.

This program will monitor files for the events such as MODIFY,CREATE and DELETE.

(Don’t forget this program requires JDK 7.0)

package watcherserviceexamplejdk7;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import static java.nio.file.StandardWatchEventKind.*;

/**
*
* @author tunatore
*/
public class WatcherServiceExampleJDK7 {

public static void main(String[] args) throws IOException, InterruptedException {
monitorFilesInDirectory("C:\\directoryname");
}

public static void monitorFilesInDirectory(String directory) {

try {
//create a WatcherService object for monitoring directories
WatchService watchService = FileSystems.getDefault().newWatchService();
//getting the path object for the directory given by users
Path path = Paths.get(directory);
//register the events to be notified by the program
path.register(watchService, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
while (true) {
//infinite loop will take events
WatchKey key = watchService.take();
for (WatchEvent<?> watchEvent : key.pollEvents()) {
//getting the type of the event
WatchEvent.Kind<?> kind = watchEvent.kind();
//getting the file name from the WatchEvent object
Path file = (Path) watchEvent.context();
System.out.println("Filename --> " + file + " Event type --> " + kind.name());
}
//reset the current event and wait for other events
key.reset();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Here is an example output for the program;

processes taken in the following order

1. Created a file named abc.txt (under the directory)
2. Modified abc.txt

3. Deleted abc.txt file

Filename –> New Text Document.txt Event type –> ENTRY_CREATE
Filename –> New Text Document.txt Event type –> ENTRY_DELETE
Filename –> abc.txt Event type –> ENTRY_CREATE

Filename –> abc.txt Event type –> ENTRY_MODIFY
Filename –> abc.txt Event type –> ENTRY_MODIFY
Filename –> abc.txt Event type –> ENTRY_DELETE

BUILD STOPPED (total time: 1 minute 57 seconds)

Download Source Code

Advertisements

How to use String in a Switch Statement with JDK 7


Before JDK 7  using String class in a Switch statement was not allowed by Java.
Now by using JDK 7 programmers are allowed to use Strings in Switch statements.

Sample error

Exception in thread “main” java.lang.RuntimeException: Uncompilable source code – strings in switch are not supported in -source 1.6
  (use -source 7 or higher to enable strings in switch)
    at stringsinswitch.StringsInSwitch.testingSwitch(StringsInSwitch.java:20)
    at stringsinswitch.StringsInSwitch.main(StringsInSwitch.java:14)
Java Result: 1

Before JDK 7 Switch statement allows programmers to use the following values;

byte
short
char
int
Enums

With JDK 7

All of the above types + String

Sample program;

package stringsinswitch;

/**
*
* @author tunatore
*/
public class StringsInSwitch {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//JDK 7 allows programmers using Strings in Switch statement
StringsInSwitch.testingSwitch(“string1”);
StringsInSwitch.testingSwitch(“string2”);
StringsInSwitch.testingSwitch(“”);
}
public static void testingSwitch(String inStr) {

switch (inStr) {
case “string1”:
System.out.println(“string1”);
break;
case “string2”:
System.out.println(“string2”);
break;
default:
System.out.println(“inside –>  Default”);
break;
}

}
}

Output of the program;

run:
string1
string2
inside –>  Default
BUILD SUCCESSFUL (total time: 0 seconds)

How to catch more than one exception(multi-catch statement) inside a single catch block (Java JDK 7)


package exceptionhandlingjava7;

import java.sql.SQLException;
/**
 *
 * @author tunatore
 */

public class Main {

public static void main (String args[]){

//instead of coding a try catch block such as the following one

        //try {
        //    …
        //} catch (NullPointerException ex) {}
        //  catch (ArrayIndexOutOfBoundsException ex) { }
        //  catch (SQLException ex) { }
        //  catch (… ex) { }

  // Java JDK 7 users can use multi-catch statement in one line

try {
throw new ArrayIndexOutOfBoundsException();
} catch (NullPointerException | ArrayIndexOutOfBoundsException | SQLException ex) {
ex.printStackTrace();
}
}
}

Output of the program;

run:
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException
at exceptionhandlingjava7.Main.main(Main.java:25)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 seconds)

If you don’t reference JDK 7 API in your project, you will encounter an exception like the following one;
error: multi-catch statement is not supported in -source 1.5