O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

10.5. Writing to a File

To start with, you will be using the simplest write() method for a file channel that writes the data contained in a single ByteBuffer object to a file. The number of bytes written to the file is determined by the buffer's position and limit when the write() method executes. Bytes will be 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 returns the number of bytes that were actually written as a value of type int.

A channel write() operation can throw any of five different exceptions:

ExceptionDescription
NonWritableChannelExceptionThrown if the channel was not opened for writing.
ClosedChannelExceptionThrown if the channel is closed. Calling the close() method for the file channel will close the channel, as will calling the close() method for the file stream.
AsynchronousCloseExceptionThrown if another thread closes the channel while the write operation is in progress.
ClosedByInterruptExceptionThrown if another thread interrupts the current thread while the write operation is in progress.
IOExceptionThrown if some other I/O error occurs.

The first of these is a subclass of RuntimeException, so you do not have to catch this exception. The other four are subclasses of IOException, which must be caught, so you will normally put the write() method call in a try block. If you want to react specifically to ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required