Java Reference
In-Depth Information
} catch ( IOException e ) {
// ...
}
We're making use of the StandardOpenOption enum, which provides similar capa‐
bilities to the copy options, but for the case of opening a new file instead.
In this example use case, we have used the Path API to:
• Create a Path corresponding to a new file
• Use the Files class to create that new file
• Open a Writer to that file
• Write to that file
• Automatically close it when done
In our next example, we'll build on this to manipulate a .jar file as a FileSystem in
its own right, modifying it to add an additional file directly into the JAR. JAR files
are just ZIP files, so this technique will also work for .zip archives:
Path tempJar = Paths . get ( "sample.jar" );
try ( FileSystem workingFS =
FileSystems . newFileSystem ( tempJar , null )) {
Path pathForFile = workingFS . getPath ( "/hello.txt" );
List < String > ls = new ArrayList <>();
ls . add ( "Hello World!" );
Files . write ( pathForFile , ls , Charset . defaultCharset (),
StandardOpenOption . WRITE , StandardOpenOption . CREATE );
}
This shows how we use a FileSystem to make the Path objects inside it, via the
getPath() method. This enables the developer to effectively treat FileSystem
objects as black boxes.
One of the criticisms of Java's original I/O APIs was the lack of support for native
and high-performance I/O. A solution was initially added in Java 1.4, the Java New
I/O (NIO) API, and it has been successively refined in successive Java versions.
NIO Channels and Bufers
NIO buffers are a low-level abstraction for high-performance I/O. They provide a
container for a linear sequence of elements of a specific primitive type. We'll work
with the ByteBuffer (the most common case) in our examples.
ByteBufer
This is a sequence of bytes, and can conceptually be thought of as a performance-
critical alternative to working with a byte[] . To get the best possible performance,
Search WWH ::




Custom Search