Skip to content

Commit

Permalink
Close BufferedSource in README sample
Browse files Browse the repository at this point in the history
  • Loading branch information
NightlyNexus committed Feb 8, 2017
1 parent 11ad43e commit 44170a2
Showing 1 changed file with 18 additions and 20 deletions.
38 changes: 18 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,27 +78,25 @@ Decoding the chunks of a PNG file demonstrates Okio in practice.
private static final ByteString PNG_HEADER = ByteString.decodeHex("89504e470d0a1a0a");

public void decodePng(InputStream in) throws IOException {
BufferedSource pngSource = Okio.buffer(Okio.source(in));

ByteString header = pngSource.readByteString(PNG_HEADER.size());
if (!header.equals(PNG_HEADER)) {
throw new IOException("Not a PNG.");
}

while (true) {
Buffer chunk = new Buffer();

// Each chunk is a length, type, data, and CRC offset.
int length = pngSource.readInt();
String type = pngSource.readUtf8(4);
pngSource.readFully(chunk, length);
int crc = pngSource.readInt();

decodeChunk(type, chunk);
if (type.equals("IEND")) break;
try (BufferedSource pngSource = Okio.buffer(Okio.source(in))) {
ByteString header = pngSource.readByteString(PNG_HEADER.size());
if (!header.equals(PNG_HEADER)) {
throw new IOException("Not a PNG.");
}

while (true) {
Buffer chunk = new Buffer();

// Each chunk is a length, type, data, and CRC offset.
int length = pngSource.readInt();
String type = pngSource.readUtf8(4);
pngSource.readFully(chunk, length);
int crc = pngSource.readInt();

decodeChunk(type, chunk);
if (type.equals("IEND")) break;
}
}

pngSource.close();
}

private void decodeChunk(String type, Buffer chunk) {
Expand Down

0 comments on commit 44170a2

Please sign in to comment.