Java Reference
In-Depth Information
Note
As an example of how the NIO2 API improves file I/O in Java, consider
the “read a grocery list” example provided earlier. Using NIO2, this code frag-
ment can be rewritten as follows:
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class ShowGroceries {
public static void main(String[] args) {
List<String> groceries = new ArrayList<>();
try {
groceries = Files.readAllLines(
Paths.get("groceries.txt"),
Charset.defaultCharset());
} catch (IOException | SecurityException e) {
e.printStackTrace();
}
for (String item : groceries) {
System.out.println("Don't forget to pickup: " + item);
}
}
}
Notice the
readAllLines
method, which removes the burden of having to use
the
FileReader
and
BufferedReader
classes.
You are now ready to delve into I/O with Java for real and explore the concept of streams in more detail.
streams
We've mentioned before that the key abstraction behind I/O in Java is the concept of a stream.
Streams represent a sequence of data as it is read from a source (an input stream) or written to a des-
tination (an output stream). This immediately clarifies why you will not deal with file modes in Java
(opening a file for reading or writing), as the type of stream (input or output) will determine whether
you want to use a file as a data source or destination.
We've also stated that streams can support different kinds of data, and depending on the data type
they carry, different methods are exposed. For streams carrying textual data, for instance (think
back on text files), it makes sense to read in a single text line. For streams carrying byte data (raw
bits and bytes), no concept of a “text line” can be defined, so this method does not make sense in
this context. Apart from reading and writing data, streams can also modify or transform data as it
passes through. A common example is an output stream that zips (compresses) the data while writ-
ing it to a file, in order to reduce the file size.
Search WWH ::
Custom Search