Java Reference
In-Depth Information
e.printStackTrace();
System.exit(1);
}
try(BufferedWriter fileOut = Files.newBufferedWriter(
file,
Charset.forName("UTF-16"))){
// Write saying to the file
for(int i = 0 ; i < sayings.length ; ++i) {
fileOut.write(sayings[i], 0, sayings[i].length());
fileOut.newLine();
// Write separator
}
System.out.println("File written.");
} catch(IOException e) {
System.err.println("Error writing file: " + file);
e.printStackTrace();
}
}
}
WriterOutputToFile.java
The only output is the file path and confirmation that the file was written.
How It Works
As in the previous example, the directory to contain the file is the "Beginning Java Stuff" directory in
your home directory and you make sure the directory does exist. The BufferedWriter class implements
the AutoCloseable interface so we create the object in a try block with resources. Each element in the
sayings array is written to the file in the loop using the write() method. The default options are in effect
for the BufferedWriter object, WRITE , CREATE , and TRUNCATE_EXISTING , so a new file is created if it
doesn't already exist and any file contents are overwritten. A newline character is written to the file by
calling the newLine() method after each saying. This allows the sayings to be separated when the file is
read.
The third method for writing files involves the use of channels . A channel is a mechanism for transferring
data to and from an external source using buffers. Using a channel is considerably more powerful and flex-
ible than using an output stream or a writer so I will spend more time on this than the first two. However,
there's something I need to explain before you can use a channel to write file.
All the data that you write to a file using a channel starts out in one or more buffers in memory. Similarly,
when you read from a file using a channel, the data from the file ends up in one or more buffers and you
access it from there. The Java library provides an extensive range of capabilities for working with buffers,
and these are essential when using the newByteChannel() route to writing a file. I will explain the various
ways in which you can create and use buffers before getting into writing files using channels.
BUFFERS
All the classes that define buffers have the abstract java.nio.Buffer class as a base. The Buffer class
therefore defines the fundamental characteristics common to all buffers. Each buffer class type can store a
Search WWH ::




Custom Search