Java Reference
In-Depth Information
Next, in the
try
block you create the channel for each file from the
Path
objects:
try (FileChannel inCh =
(FileChannel)(Files.newByteChannel(fromFile));
WritableByteChannel outCh = Files.newByteChannel(
toFile,
EnumSet.of(WRITE,CREATE_NEW))){
There are two
FileChannel
objects that you want to be automatically closed, so you create both between
the parentheses following the
try
keyword. The
inCh
file channel has the
READ
option specified by de-
fault. You specify the
WRITE
and
CREATE_NEW
options for
outCh
, which guarantees the backup file is
a new file. If the backup file already exists, the
getByteChannel()
method would fail. However, this
should not happen because you have already verified that the backup file path does not reference a file
that already exists.
After you have the channel objects, you transfer the contents of the input file to the output file in the
try
block like this:
int bytesWritten = 0;
long byteCount = inCh.size();
while(bytesWritten<byteCount) {
bytesWritten += inCh.transferTo(bytesWritten,
byteCount-bytesWritten,
outCh);
}
You copy the data using the
transferTo()
method for
inCh
. The chances are good that the
transfer-
To()
method transfers all the data in one go. The
while
loop is there just in case it doesn't. The loop
condition checks whether the number of bytes written is less than the number of bytes in the file. If it is,
the loop executes another transfer operation for the number of bytes left in the file, with the file position
specified as the number of bytes written so far.
RANDOM ACCESS TO A FILE
The
FileChannel
class defines
read()
and
write()
methods that operate at a specified position in the file:
•
read(ByteBuffer buf, long position)
reads bytes from the file into
buf
in the same way as
you have seen previously except that bytes are read starting at the file position specified by the
second argument. The channel's position is not altered by this operation. If
position
is greater
than the number of bytes in the file, then no bytes are read.
•
write(ByteBuffer buf, long position)
writes bytes from
buf
to the file in the same way as
you have seen previously except that bytes are written starting at the file position specified by the
second argument. The channel's position is not altered by this operation. If
position
is less than
the number of bytes in the file then bytes from that point are overwritten. If
position
is greater
than the number of bytes in the file then the file size is increased to this point before bytes are
written. In this case the bytes between the original end-of-file and where the new bytes are written
contain junk values.