Java Reference
In-Depth Information
The
write()
method for the
FileChannel
object writes the contents of the buffer to the file. When the
try
block ends, the
close()
method for the channel is called automatically to close the channel and re-
lease the resources associated with it, including the file.
FILE WRITE OPERATIONS
You have used only the simplest
write()
method for a
FileChannel
object to write all the data contained
in a single
ByteBuffer
object to a file. Write operations can be more complicated in three ways:
1.
You can arrange that only part of the data in a
ByteBuffer
is written to the file.
2.
You can use
write()
methods declared in the
GatheringByteChannel
interface that write data from
multiple buffers to a file in a single operation.
3.
You can write to random position in a file.
Let's explore each of these possibilities in a little more detail.
Writing Part of a Buffer to a File
So far you have not been concerned with the buffer's limit and position in the examples. As you know, a
buffer's position and limit determines the number of bytes written to the file when the
write()
method ex-
ecutes. Bytes are written starting with the byte at the buffer's current position. The number of bytes written
is
limit-position
, which is the number returned by the
remaining()
method for the buffer object. The
write()
method that writes a single buffer returns the number of bytes that were actually written as a value
of type
int
.
Let's try an example that shows how the buffer's position and limit change during operations with the
buffer.
TRY IT OUT: Buffer State during a Channel Write
You write the string
"Garbage in, garbage out\n"
to a file with the name
charData.txt
in the
Junk
directory. If you want to write to a file that is different from the example, just change the path accord-
ingly. Here is the code:
import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
import java.nio.channels.*;
import java.util.EnumSet;
import java.io.IOException;
import java.nio.ByteBuffer;