Today is Wednesday, 29th March 2017

Archive for April, 2014

Watching files in Java with WatchService

Java 7 introduced a useful API for watching files on the file system. This feature comes in handy if you need to scan a directory for new files or modified files. The API is event driven, so the system will notify you of certain events such as “new file”, “modified file” or “deleted file”.

The example below demonstrates the key features of the WatchService API. It scans a given directory for file events and calls the appropriate handle methods. Inside of the handler methods, you can provide your own custom handling. It is important to note that a separate event is generated for each file. So for example, if you add 10 new files to the directory, then it will generate 10 new events.

 

Share


Iterating a HashMap

Here is a quick example that shows how to iterate over a HashMap.

You have the option of using the map key set or the map entry set.

 

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class HashDemo {
public static void main(String[] args) {
Map<String, String> theMap = new HashMap<String, String>();
theMap.put("alfa", "john");
theMap.put("beta", "mary");
theMap.put("code", "susan");
// iterate using keys
System.out.println("Using Key set");
Set<String> theKeys = theMap.keySet();
for (String tempKey : theKeys) {
String tempValue = theMap.get(tempKey);
System.out.println("key: " + tempKey + ", value: " + tempValue);
}
// iterator using Map.Entry
System.out.println("\nUsing Map.Entry");
Set<Map.Entry<String, String>> theMapEntries = theMap.entrySet();
for (Map.Entry<String, String> tempEntry : theMapEntries) {
System.out.println("key: "  + tempEntry.getKey() + ", value: "  + tempEntry.getValue());
}
}
}
Share