Java Reference
In-Depth Information
try {
groceries = Files.readAllLines(
Paths.get("groceries.txt"),
Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
}
for (String item : groceries) {
System.out.println("Don't forget to pickup: " + item);
}
}
}
Similarly, two methods exist to write all bytes or lines to a file:
Path write(Path path, byte[] bytes, OpenOption... options) : Writes bytes to a
file. By default, this method creates a new file or overwrites an existing file.
Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs,
OpenOption... options) : Writes lines of text to a file. By default, this method creates a
new file or overwrites an existing file. Don't be confused by the signature of the lines argu-
ment. In practical cases, this will work with a List<String> , for instance. The Charset
parameter specifies which character set should be used for encoding the file. Using Charset.
defaultCharset() or Charset.forName("UTF-8") works best in most cases.
You might be wondering what the OpenOptions parameters are for in these methods. These options
are used in various methods and will tell the NIO2 API how you want to open the file. You can pass
in the following StandardOpenOptions values:
WRITE : Opens a file for write access.
APPEND : Appends new data to the end of the file (use together with WRITE or CREATE ).
TRUNCATE_EXISTING : Empties the file before writing (use with WRITE ).
CREATE_NEW : Creates a new file or throws an exception if the file exists.
CREATE : Opens the file or creates it if it does not exist.
DELETE_ON_CLOSE : Deletes the file when the handling stream is closed.
SPARSE , SYNC , DSYNC : A set of advanced options that we do not describe in detail here.
If you've been paying attention, you'll notice that these options strongly resemble the file operation
modes introduced in the beginning of this chapter. In most cases, there's no need to provide any
options at all, however, as the API will assume sensible defaults when you leave them out ( CREATE ,
TRUNCATE_EXISTING , and WRITE for the write methods, for instance). When you do supply your
own options, take care not to supply an infeasible combination or a combination that does not
match the operation you're trying to perform with the method you're calling.
The methods mentioned so far are fine when you're dealing with small files, but when you need to
work with large files, you cannot store the contents of the file in memory all at the same time. We
already know how we would approach this problem using buffered character streams:
Search WWH ::




Custom Search