Reading the content of an InputStream
as a byte
array:
// Reading from a file
try (InputStream in = new FileInputStream("in.dat")) {
byte[] content = ByteStreams.toByteArray(in);
// do something with content
}
Copying an InputStream
to an 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);
}
Note: to copy files directly, it's better to use Files.copy(sourceFile, destinationFile)
.
Reading an entire predefined byte
array from an InputStream
:
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.
}
Skipping n
bytes from the InputStream
:
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.
}
Creating an OutputStream
that discards everything that is written to it:
try (InputStream in = new FileInputStream("in.dat");
OutputStream out = ByteStreams.nullOutputStream()) {
ByteStreams.copy(in, out);
// The whole content of in is read into... nothing.
}