Java Reference
In-Depth Information
System.exit(1);
}
// Get the channel for the file
FileChannel outputChannel = outputFile.getChannel();
The FileChannel class implements all of the channel interfaces that we discussed in the previous
section, so any FileChannel object incorporates the methods we have seen for both reading and
writing a file. However, a FileChannel object obtained from a FileOutputStream object will not
be able to read from the file since the stream only permits output. Similarly, a FileChannel obtained
from a FileInputStream object can only read from the file. If you try to perform a read operation on
a file opened just for output, a NonReadableChannelException will be thrown. Attempting to write
to a file opened for input will result in a NonWritableChannelException being thrown.
Once you have obtained a reference to a file channel, you are ready to read from or write to the file, but
we need to learn a bit more about buffers before we can try that out.
Buffers
All the classes that define buffers have the abstract class Buffer as a base. The Buffer class therefore
defines the fundamental characteristics common to all buffers. A particular buffer can store a sequence of
elements of a given type, and an element can be of any primitive data type other than boolean . Thus, you
can create buffers to store byte values, char values, short values, int values, long values, float values,
or double values. The following classes in the java.nio package define these buffers:
Class
Description
ByteBuffer
A buffer that stores elements of type byte . You can also store the
binary values of any of the other primitive types in this buffer,
except for type boolean . Each binary value that you store will
occupy a number of bytes in the buffer determined by the type -
values of type char or short will occupy two bytes, int values will
occupy four bytes, and so on. Only buffers of this type can be used
in a file I/O operation.
CharBuffer
A buffer that only stores elements of type char .
ShortBuffer
A buffer that only stores elements of type short .
IntBuffer
A buffer that only stores elements of type int .
LongBuffer
A buffer that only stores elements of type long .
FloatBuffer
A buffer that only stores elements of type float .
DoubleBuffer
A buffer that only stores elements of type double .
Search WWH ::




Custom Search