處理現有的讀者和作家
將 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.
}