Skip to content

Commit ed440e9

Browse files
jean-philippe-martinmziccard
authored andcommitted
Close channel and fix typo (#1036)
1 parent 441918b commit ed440e9

2 files changed

Lines changed: 21 additions & 20 deletions

File tree

gcloud-java-examples/src/main/java/com/google/cloud/examples/nio/CountBytes.java

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -71,25 +71,26 @@ private static void countFile(String fname) {
7171
ByteBuffer buf = ByteBuffer.allocate(bufSize);
7272
System.out.println("Reading the whole file...");
7373
Stopwatch sw = Stopwatch.createStarted();
74-
SeekableByteChannel chan = Files.newByteChannel(path);
75-
long total = 0;
76-
int readCalls = 0;
77-
MessageDigest md = MessageDigest.getInstance("MD5");
78-
while (chan.read(buf) > 0) {
79-
readCalls++;
80-
md.update(buf.array(), 0, buf.position());
81-
total += buf.position();
82-
buf.flip();
83-
}
84-
readCalls++; // We must count the last call
85-
long elapsed = sw.elapsed(TimeUnit.SECONDS);
86-
System.out.println("Read all " + total + " bytes in " + elapsed + "s. " +
87-
"(" + readCalls +" calls to chan.read)");
88-
String hex = String.valueOf(BaseEncoding.base16().encode(md.digest()));
89-
System.out.println("The MD5 is: 0x" + hex);
90-
if (total != size) {
91-
System.out.println("Wait, this doesn't match! We saw " + total + " bytes, " +
92-
"yet the file size is listed at " + size + " bytes.");
74+
try (SeekableByteChannel chan = Files.newByteChannel(path)) {
75+
long total = 0;
76+
int readCalls = 0;
77+
MessageDigest md = MessageDigest.getInstance("MD5");
78+
while (chan.read(buf) > 0) {
79+
readCalls++;
80+
md.update(buf.array(), 0, buf.position());
81+
total += buf.position();
82+
buf.flip();
83+
}
84+
readCalls++; // We must count the last call
85+
long elapsed = sw.elapsed(TimeUnit.SECONDS);
86+
System.out.println("Read all " + total + " bytes in " + elapsed + "s. " +
87+
"(" + readCalls +" calls to chan.read)");
88+
String hex = String.valueOf(BaseEncoding.base16().encode(md.digest()));
89+
System.out.println("The MD5 is: 0x" + hex);
90+
if (total != size) {
91+
System.out.println("Wait, this doesn't match! We saw " + total + " bytes, " +
92+
"yet the file size is listed at " + size + " bytes.");
93+
}
9394
}
9495
} catch (Exception ex) {
9596
System.out.println(fname + ": " + ex.toString());

gcloud-java-examples/src/main/java/com/google/cloud/examples/nio/ParallelCountBytes.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ public WorkUnit call() throws IOException {
7979
return this;
8080
}
8181
chan.position(pos);
82-
// read until buffer it is full, or EOF
82+
// read until buffer is full, or EOF
8383
while (chan.read(buf) > 0) {};
8484
return this;
8585
}

0 commit comments

Comments
 (0)