Reading the content of a Reader
as a String
:
// Reading from a file
try (Reader reader = new FileReader("in.txt")) {
String content = CharStreams.toString(reader);
// do something with content
}
Reading the content of a Reader
as a list of line contents:
try (Reader reader = new FileReader("in.txt")) {
List<String> lines = CharStreams.readLines(reader);
for (String line: lines) {
// Do something with line
}
}
Copying a Reader
to a Writer
:
try (Reader reader = new FileReader("in.txt");
Writer writer = new FileWriter("out.txt")) {
CharStreams.copy(reader, writer);
}
Note: to copy files directly, it's better to use Files.copy(sourceFile, destinationFile).
Skipping n
bytes from the Reader
:
try (Reader reader = new FileReader("in.txt")) {
CharStreams.skipFully(reader, 20);
// The next char read will be the 21st.
} catch (EOFException e) {
// There was less than 20 chars in the Reader.
}
Creating a Writer
that discards everything that is written to it:
try (Reader reader = new FileReader("in.txt");
Writer writer = CharStreams.nullWriter()) {
CharStreams.copy(reader, writer);
// The whole content of reader is read into... nothing.
}