处理现有的 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.
}