处理现有的读者和作家

Reader 的内容读作 String

// Reading from a file
try (Reader reader = new FileReader("in.txt")) {
  String content = CharStreams.toString(reader);
  // do something with content
}

读取 Reader 的内容作为行内容列表:

try (Reader reader = new FileReader("in.txt")) {
  List<String> lines = CharStreams.readLines(reader);
  for (String line: lines) {
    // Do something with line
  }
}

Reader 复制到 Writer

try (Reader reader = new FileReader("in.txt");
     Writer writer = new FileWriter("out.txt")) {
  CharStreams.copy(reader, writer);
}

注意:要直接复制文件,最好使用 Files.copy(sourceFile, destinationFile)。

Reader 中跳过 n 个字节:

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.
}

创建一个丢弃写入其中的所有内容的 Writer

try (Reader reader = new FileReader("in.txt");
     Writer writer = CharStreams.nullWriter()) {
  CharStreams.copy(reader, writer);
  // The whole content of reader is read into... nothing.
}