Sunday, August 18, 2013

Java New IO 2.0

The New IO is one of the features introduced in Java7. A new package java.nio has been added as part of this feature. Even though the usage wise it's same as java.io, most of the issues in java.io has been addressed. We will see the features introduced in New IO (NIO)
Path
The package java.nio.file consists of classes and interfaces Path, Paths, FileSystem, FileSystems and others. Each of represent's the file path or file system as is.
java.nio.file.Path works exactly same as java.io.File with additional features.
Path path = Paths.get("C:\\temp\\sample.txt");
System.out.println("Name Count : "+path.getNameCount());
System.out.println("Parent     : "+path.getParent());
System.out.println("Root       : "+path.getRoot());
The output will be
Name Count : 2
Parent     : C:\temp
Root       : C:\
Files
Path can also be used for deleting. There are two delete methods. One delete method can throw NoSuchFileException if the file doesn't exist.
Files.delete(path);
Where as other deletes the file if exists.
Files.deleteIfExists(path);
There are copy, move, create (Both for directories and files) with options. There are mthods to create symbolic links, temporary directories as well.
WatchService
This is the service which we can get the file change notifications like delete, update, create, change etc. WatchService API makes to receive notifications on a file or directory.
   Path path = Paths.get("C:\\Temp");
   WatchService service = path.getFileSystem().newWatchService();
   path.register(service, StandardWatchEventKinds.ENTRY_CREATE,
            StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY);
   WatchKey watckKey = service.take();
   List<watchevent>&gt; events = watckKey.pollEvents();
   for(WatchEvent event : events)
   {
       System.out.println("Event : "+event.kind().name()+"; Context : "+event.context());
   }
The steps for creating a WatchService are
  • Create WatchService instance using path
  • Register required events (Create, delete and modify are available) on the path
  • Get the watch key and poll for the events. (For continuously watching the events, put it in infinite loop).
Happy Learning!!!

No comments:

Post a Comment