Java Reference
In-Depth Information
•
ClosedByInterruptException
: Thrown if another thread interrupts the current thread while the
write operation is in progress.
•
IOException
: Thrown if some other I/O error occurs.
The first three are subclasses of
IOException
, which must be caught, so you generally put the
write()
method call in a
try
block. Typically this beis a
try
block with resources in which you create the channel
so you get the
close()
method called automatically. If you want to react specifically to one or other of first
three exceptions, you need to add a
catch
block for that specific type. Otherwise, you can just include a
single
catch
block for type
IOException
to catch all four types of exception.
Let's try a simple example.
TRY IT OUT: Creating a Channel and Writing to a File
This example creates a file and uses a channel to write some text to it:
import static java.nio.file.StandardOpenOption.*;
import java.nio.channels.WritableByteChannel;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.EnumSet;
import java.nio.file.*;
public class TryChannel {
public static void main(String[] args) {
String[] sayings = {
"The more you plan the luckier you get.",
"The time to complete a project is the time " +
"one person would need to complete it " +
"multiplied by the number of people on the project.",
"If at first you don't succeed, remove any evidence that you
tried.",
"A clever person solves problems, a wise person avoids them.",
"Death is nature's way of telling you to slow down.",
"A hen is an egg's way of making other eggs.",
"The earlier you begin coding the later you finish.",
"Anything you can't understand is intuitively obvious."};
String separator = System.lineSeparator();
Path file = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java
Stuff").resolve("MoreSayings.txt");
try {
// Create parent directory if it doesn't exist
Files.createDirectories(file.getParent());
} catch(IOException e) {