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 :

  1. JDK 7

  2. Eclipse 3.7

Download :

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
File Tree
console

 

Download Source Code

SrcCodes : JDK7FileOP.zip

 

References