@@ -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 ());
0 commit comments