處理現有的 InputStreams 和 OutputStreams
讀取 InputStream
的內容作為 byte
陣列:
// Reading from a file
try (InputStream in = new FileInputStream("in.dat")) {
byte[] content = ByteStreams.toByteArray(in);
// do something with content
}
將 InputStream
複製到 OutputStream
:
// Copying the content from a file in.dat to out.dat.
try (InputStream in = new FileInputStream("in.dat");
OutputStream out = new FileOutputStream("out.dat")) {
ByteStreams.copy(in, out);
}
注意:要直接複製檔案,最好使用 Files.copy(sourceFile, destinationFile)
。
從 InputStream
讀取整個預定義的 byte
陣列:
try (InputStream in = new FileInputStream("in.dat")) {
byte[] bytes = new byte[16];
ByteStreams.readFully(in, bytes);
// bytes is totally filled with 16 bytes from the InputStream.
} catch (EOFException ex) {
// there was less than 16 bytes in the InputStream.
}
從 InputStream
中跳過 n
位元組:
try (InputStream in = new FileInputStream("in.dat")) {
ByteStreams.skipFully(in, 20);
// the next byte read will be the 21st.
int data = in.read();
} catch (EOFException e) {
// There was less than 20 bytes in the InputStream.
}
建立一個丟棄寫入其中的所有內容的 OutputStream
:
try (InputStream in = new FileInputStream("in.dat");
OutputStream out = ByteStreams.nullOutputStream()) {
ByteStreams.copy(in, out);
// The whole content of in is read into... nothing.
}