Java Reference
In-Depth Information
• Nonblocking operations for filesystems not supported
g
d O
To deal with these shortcomings, Java's I/O has evolved over several major releases.
It was really with the release of Java 7 that this support became truly easy and effec‐
tive to use.
e
Modern Java I/O
Java 7 brought in a brand new I/O API—usually called NIO.2—and it should be
considered almost a complete replacement for the original File approach to I/O.
The new classes are contained in the java.nio.file package.
The new API that was brought in with Java 7 is considerably easier to use for many
use cases. It has two major parts. The first is a new abstraction called Path (which
can be thought of as representing a file location, which may or may not have any‐
thing actually at that location). The second piece is lots of new convenience and
utility methods to deal with files and filesystems. These are contained as static
methods in the Files class.
Files
For example, when using the new Files functionality, a basic copy operation is now
as simple as:
File inputFile = new File ( "input.txt" );
try ( InputStream in = new FileInputStream ( inputFile )) {
Files . copy ( in , Paths . get ( "output.txt" ));
} catch ( IOException ex ) {
ex . printStackTrace ();
}
Let's take a quick survey of some of the major methods in Files —the operation of
most of them is pretty self-explanatory. In many cases, the methods have return
types. We have omitted handling these, as they are rarely useful except for contrived
examples, and for duplicating the behavior of the equivalent C code:
Path source , target ;
Attributes attr ;
Charset cs = StandardCharsets . UTF_8 ;
// Creating files
//
// Example of path --> /home/ben/.profile
// Example of attributes --> rw-rw-rw-
Files . createFile ( target , attr );
// Deleting files
Files . delete ( target );
boolean deleted = Files . deleteIfExists ( target );
// Copying/Moving files
Search WWH ::




Custom Search