Given the code fragment:
static void addContent () throws Exception {
Path path = Paths.get("D:\\company\\report.txt");
UserPrincipal owner =
path.getFileSystem().getUserPrincipalLookupService().lookupPrincipalByName("Bob");
Files.setOwner(path, owner);
// insert code here – Line **
br.write("this is a text message ");
}
System.out.println("success");
}
Assume that the report.txt file exists.
Which try statement, when inserted at line **, enables appending the file content without writing
the metadata to the underlying disk?
A.
try (BufferWriter br = Files.newBufferedWriter (path, Charset.forName (“UTF-8”), new
openOption []
{StandardOpenOption.CREATE, StandardOpenOption.Append, StandardOpenOption.DSYNC}};}
{
B.
try (BufferWriter br = Files.newBufferedWriter (path, Charset.forName (“UTF-8”), new
openOption [] {StandardOpenOption.APPEND, StandardOpenOption.SYNC));){
C.
try (BufferWriter br = Files.newBufferedWriter (path, Charset.forName (“UTF – 8”), new
openOption [] {StandardOpenOption.APPEND, StandardOpenOption.DSYNC}
D.
try (BufferWriter br = Files.newBufferedWriter (path, Charset.forName (“UTF–8”), new
openOption []
{StandardOpenOption.CREATENEW, StandardOpenOption.APPEND,
StandardOpenOption.SYNC}}
}
E.
try (BufferWriter br = Files.newBufferedWriter (path, Charset.forName (“UTF – 8”), new
openOption [] {StandardOpenOption.APPEND, StandardOpenOption.ASYNC});) {
Explanation:
StandardOpenOption should be both APPEND (if the file is opened for WRITE
access then bytes will be written to the end of the file rather than the beginning)and DSYNC
(Requires that every update to the file’s content be written synchronously to the underlying storage
device.).
Note 1:The newBufferedWriter method Opens or creates a file for writing, returning a
BufferedWriter that may be used to write text to the file in an efficient manner. The options
parameter specifies how the the file is created or opened. If no options are present then this
method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In
other words, it opens the file for writing, creating the file if it doesn’t exist, or initially truncating an
existing regular-file to a size of 0 if it exists.
Note2: public static final StandardOpenOption APPEND
If the file is opened for WRITE access then bytes will be written to the end of the file rather than
the beginning.
If the file is opened for write access by other programs, then it is file system specific if writing to
the end of the file is atomic.
Reference: java.nio.file.Files
java.nio.file Enum StandardOpenOption