Reading and Writing Files Using Paths – Java I/O: Part II

21.5 Reading and Writing Files Using Paths

The Files class provides methods for reading and writing bytes and characters using I/O streams and Path objects.

Methods provided for reading and writing files typically close the file after use.

Open Options

The java.nio.file.OpenOption interface is implemented by objects that can be specified as options to configure how a file operation should open or create a file. Methods for writing to files can be configured for this purpose by specifying constants defined by the enum type java.nio.file.StandardOpenOption that implements the OpenOption interface.

Table 21.9 shows the options defined by constants of the StandardOpenOption enum type. Such options are specified as values for the variable arity parameter of type OpenOption in methods such as newBufferedWriter(), write(), writeString(), newOutputStream(), and newInputStream() of the Files class.

For write operations, if no options are supplied, it implies that the following options for opening and creating a file are present: CREATE, TRUNCATE_EXISTING, and WRITE—meaning the file is opened for writing, created if it does not exist, and truncated to size 0.

Table 21.9 Selected Standard Open Options

Enum java.nio.file.StandardOpenOption implements the java.nio.file.OpenOption interfaceDescription
READOpen the file for read access.
WRITEOpen the file for write access.
APPENDIf the file is opened for WRITE access, write bytes to the end of the file. That is, its previous content is not overwritten.
TRUNCATE_EXISTINGIf the file already exists and it is opened for WRITE access, truncate its length to 0 so that bytes are written from the beginning of the file.
CREATEOpen the file if it exists; otherwise, create a new file.
CREATE_NEWFail if the file already exists; otherwise, create a new file.
DELETE_ON_CLOSEDelete the file when the stream is closed. Typically used for temporary files.
Categories: ,

Leave a Reply

Your email address will not be published. Required fields are marked *