Java Reference
In-Depth Information
Obtaining a Channel for a File
To obtain a channel for a file, you call the static newByteChannel() method from the Files class. The first
argument is a Path object that encapsulates the file path. The second argument specifies an EnumSet of op-
tions from the java.nio.file.StandardOpenOption enumeration that you have already seen. This set of
options specifies how you want to work with the file. You used an EnumSet object to hold enum constants
in the previous chapter when you implemented walking a file tree, and you learn about the details of the
EnumSet class in Chapter 14.
The newByteChannel() method returns a FileChannel object as a reference of type
java.nio.channels.SeekableByteChannel . However, ideally you should store the reference returned by
the newByteChannel() method in a variable of the interface type that suits what you want to do with the
channel and that corresponds with the options you have set. For example, if you are simply writing a file,
use WritableByteChannel as the variable type that holds the reference returned by the newByteChannel()
method or if you are reading a file use ReadableByteChannel .
NOTE Although the newByteChannel() method returns a reference to an object of type
FileChannel , you cannot store the reference directly in a variable of this type. You can only
storethereferenceastype SeekableByteChannel , oroneoftheinterfacetypesthatthe Seek-
ableByteChannel interface extends. To store the reference as type FileChannel , you must
explicitly cast it to that type.
The following statements create a channel:
Path file = Paths.get("D:\Junk\mydata.txt");
WritableByteChannel fileOut = Files.newByteChannel(
file, EnumSet.of(WRITE, CREATE, TRUNCATE_EXISTING));
This creates a channel that can write the file specified by the file path. If the file does not exist, it is
created and any existing contents are overwritten. The newByteChannel() method can throw several excep-
tions:
IllegalArgumentException if you supply an invalid set of options.
FileAlreadyExistsException if you specify the CREATE_NEW option and the file already exists.
IOException if an I/O error occurs.
The method can also throw SecurityException if access to the file is prevented by a security manager.
Channel Write Operations
The WritableByteChannel interface declares a single method, write() that returns the number of bytes
written as type int . The argument is a ByteBuffer object containing the bytes to be written to the file. A
channel write() operation can throw any of the following exceptions:
ClosedChannelException : Thrown if the channel is closed.
AsynchronousCloseException : Thrown if another thread closes the channel while the write op-
eration is in progress.
Search WWH ::




Custom Search