Java Reference
In-Depth Information
OutputStream
object in a
BufferedOutputStream
object, you are able to use the
write()
meth-
od for the buffered stream object to write binary data to the file efficiently.
• The
newBufferedWriter()
method opens or creates a file specified by a
Path
object for writing
in text mode. The
BufferedWriter
object that the method returns provides an efficient way to
write textual data to a file.
• The
newByteChannel()
method opens a file specified by a
Path
object that can be accessed at
random for writing and/or reading. The data written or read can be binary or textual data.
The
Files
class also defines two static
write()
methods that can write either a
byte[]
array to a file
or an
Iterable
set of lines as characters. I'll concentrate on the three possibilities in the above list because
these are the most useful. Let's start by exploring how you can write a file using an
OutputStream
object in
more detail.
WRITING A FILE VIA AN OUTPUT STREAM
The
newOutputStream()
method in the
Files
class expects the first argument to be a
Path
object encap-
sulating the path to the file to be written. You can supply one or more optional arguments to specify open
options for the file from the
java.nio.file.StandardOpenOption
enumeration. These determine how the
file is opened and where the data goes when you write to it. You can use the options presented in
Table 10-1
in this context.
TABLE 10-1
:
Output Options Defined by the StandardOpenOption Enumeration
OPTION DESCRIPTION
CREATE
Create a new file if the file does not already exist.
CREATE_NEW
Create a new file, but fail the operation if the file already exists.
DELETE_ON_CLOSE
Delete the file when the stream is closed. This is primarily for use with work files that are only
required during execution of your program.
APPEND
Write new data to the end of the file.
TRUNCATE_EXISTING
Truncate the existing file length to 0 so new data is written from the beginning, overwriting any
previous data.
Open the file for write access.
WRITE
The enumeration also defines the following constants, as presented in
Table 10-2
.
TABLE 10-2
:
Output Options Defined by the StandardOpenOption Enumeration
OPTION DESCRIPTION
READ
Opens the file for read access.
SPARSE
Provides a hint to improve efficiency for file systems that support sparse files.
SYNC
Requires that all file updates are written synchronously to the storage device. This causes the return from the
write method to wait until all data and metadata have been written to the storage device. This is to ensure the
integrity of files in the event of a system crash.
This has the same effect as
SYNC
but only in relation to file data, not metadata.
DSYNC
You use the
READ
option in the next chapter.
If you don't specify any arguments to the
newOutputStream()
method after the first, the default options
in effect are
WRITE
,
CREATE
, and
TRUNCATE_EXISTING
. This means that by default a new file is created if