Java File and Directory operations made easy in JDK 7
Here we'll see two examples - Copy operation & Traversing a file tree. If you have already worked using JDk 6 or earlier versions then you can see how easy it is to use JDK 7's nio package. And you need to write less code to implement the same.
This tutorial shows two examples on the file IO mechanism introduced in the JDK 7. The java.nio.file package provides support for file IO and for accessing the default file system. This package provides very intuitive and easy to use file handling API. And it also reduces number of lines of code required to implement file handling related application functionalities.
Technologies used in this article :
JDK 7
Eclipse 3.7
For our example, we'll use file operations supported by java.nio.file.Files. This class contains many static methods (like copy, move, delete, walkFileTree etc.) that operate on files / directories. And these methods mostly delegate to the associated file system provider to perform the file operations.
java.nio.file.Path is one of the primary entrypoints of the java.nio.file package. Path class represents a path in the underlying file system
Example 1 : File Copy operation
To copy from source file to the target file 'Files.copy' method is used. We need to provide different options using 'java.nio.file.CopyOption' to specify how the copy should be done.
File : CopyOPDemo.java
Example 2 : Traverse a file tree
In this example we'll traverse a file tree using 'Files.walkFileTree' method. This method requires root / starting path and an implementation of 'SimpleFileVisitor' class where we have overridden two methods 'preVisitDirectory' and 'visitFile' to define what we want to do during visit of a directory and file. To make it simple we have only printed directory and file name.
File : RecursiveFileListDemo.java
Console Output
File Tree to be traversed
Download Source Code