In this short post, I will focus on the points I found interesting in java 7 new classes introduced into the package
java.nio.file.
I will not describe all this framework, the best documentation for that is the
official javadoc.
Manipulating the Path
These two classes Paths and Path are introducing some very nice methods to manipulate files path.
java.nio.files.Paths
This is the factory class, to be used for Path creation
java.nio.files.Path
This class is used to locate an object in the file system. Such instances are immutable and Thread safe.
Note that you can construct a Path which is not associated with an existing file. This new class is very easy to manipulate, you can iterate on each segment of the path easily, you do not see any more the file system separator ( except if you really want )
Useful methods :
normalize : very classic, to remove things like '..', './' , ... from the actual Path - returns the new Path without these redundant informations
relativize : return the absolute path from a relative path
toFile : return the file associated with this path
iterator() to iterate on each segment
- ...
Manipulating Files
Most of the operation on files will be done using the final class java.nio.files.Files.
Useful methods :
public static byte[] readAllBytes(Path path) : we all did it ourself, or by using well-known libs.
public static long copy(Path source,OutputStream out) : avoid a lot of code to copy a file in an already opened stream
static Path move(Path source, Path target, CopyOption... options): without this weird boolean result returned in the former file API. You should simply rely on the exception thrown in case of problem. See enum StandardCopyOption.
- ...
Watching a Directory for Changes
This is the killer feature I was waiting for. I was previously using some JNI extensions I did ( one for linux based on the inotify kernel feature, one based on the mac FileSystem Events Api ).
My first test illustrate the fact that the linux implementation is efficient, but the mac implementation seems to be a simple polling : not very efficient ... ( with
oracle jdk 1.7.0_05 ).
Useful classes :
java.nio.file.WatchService : the service responsible to deliver the notification to your application
java.nio.file.WatchKey : returned for each directory you are watching
Links