1.3.5. OutputStream Code Samples
From the book:
In Listing 1.1, we create a FileOutputStream to the file data.bin.gz. We decorate this with GZIPOutputStream, BufferedOutputStream, and DataOutputStream. Each link in the chain adds functionality. We then write 10 million random integers between zero and 1,000.
Listing 1.1: Writing to a DataOutputStream.
//:~ core/src/main/.../ch01/InputStreamDemo.java
try (var out = new DataOutputStream(
new BufferedOutputStream(
new GZIPOutputStream(
new FileOutputStream(
"data.bin.gz"))))) {
// write ten million random ints between 0 and 1000 to
// data.bin.gz, compressing the file with GZIP on the fly
ThreadLocalRandom.current().ints(10_000_000, 0, 1_000)
.forEach(i -> {
try {
out.writeInt(i);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
out.writeInt(-1); // our EOF marker
}
In Listing 1.2, we read from a DataInputStream, which in turn reads from BufferedInputStream, GZIPInputStream, and FileInputStream.
Listing 1.2: Reading from a DataInputStream.
//:~ core/src/main/.../ch01/InputStreamDemo.java
try (
// declared "fis" separately to ensure it is closed, even
// if the file does not contain a proper GZIP header
var fis = new FileInputStream("data.bin.gz");
var in = new DataInputStream(
new BufferedInputStream(
new GZIPInputStream(fis)))) {
long total = 0;
int value;
// keep reading until value == -1, our EOF marker
while ((value = in.readInt()) != -1) {
total += value;
}
// we expect total to be approximately 5 billion
System.out.println("total = " + total);
}
(The reason we declared the FileInputStream separately is that the GZIPInputStream reads the file header to verify that it is indeed a Gzip file. If the header is incorrect, the constructor to GZIPInputStream throws an exception, in which case the FileInputStream will not be auto-closed if we do not declare it separately.)
0 comments