Java Reference
In-Depth Information
Table 10-1. List of OpenOption Type Values That are Enum Constants in the StandardOpenOption Enum
StandardOpenOption Constant
Description
APPEND
Appends the written data to the existing file, if the file is opened for writing.
CREATE
Creates a new file, if it does not exist.
CREATE_NEW
Creates a new file, if it does not exist. If the file already exists, it fails the
operation.
DELETE_ON_CLOSE
Deletes the file when the stream is closed. It is useful when used with a
temporary file.
DSYNC
Keeps the contents of the file synchronized with the underlying storage.
READ
Opens a file with a read access.
SPARSE
If it is used with the CREATE_NEW option, it is a hint to the file system that the new
file should be a sparse file. If a sparse file is not supported by a file system, this
option is ignored.
SYNC
Keeps the content and the metadata of the file synchronized with the
underlying storage.
TRUNCATE_EXISTING
Truncates the length of an existing file to zero if the file is opened for a write
access.
WRITE
Opens a file for a write access.
The following snippet of code obtains a SeekableByteChannel object for luci2.txt file in the default directory.
It opens the file for a READ and WRITE access. It uses the CREATE option, so the file is created if it does not exist.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.channels.SeekableByteChannel;
import static java.nio.file.StandardOpenOption.READ;
import static java.nio.file.StandardOpenOption.WRITE;
import static java.nio.file.StandardOpenOption.CREATE;
...
Path src = Paths.get("luci2.txt");
SeekableByteChannel sbc = Files.newByteChannel(src, READ, WRITE, CREATE);
Listing 10-7 demonstrates how to read and display the contents of a file luci1.txt in your default directory.
The program displays an error message if the file does not exist.
Listing 10-7. Using the Files.readAllLines( ) Method to Read Contents of a File
// ReadAllLines.java
package com.jdojo.nio2;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
 
Search WWH ::




Custom Search