Hashing files/bytes <was> Re: RFR(JDK11/NIO) 8202285: (fs) Add a method to Files for comparing file contents
Paul Sandoz
paul.sandoz at oracle.com
Mon Apr 30 22:37:57 UTC 2018
Thanks, better then i expected with the transferTo method we recently added, but i think we could do even better for the ease of use case of “give me the hash of this file contents or these bytes or this byte buffer".
Paul.
> On Apr 30, 2018, at 3:23 PM, Remi Forax <forax at univ-mlv.fr> wrote:
>
>>
>> To Remi’s point this might dissuade/guide developers from using this method when
>> there are other more efficient techniques available when operating at larger
>> scales. However, it is unfortunately harder that it should be in Java to hash
>> the contents of a file, a byte[] or ByteBuffer, according to some chosen
>> algorithm (or a good default).
>
> it's 6 lines of code
>
> var digest = MessageDigest.getInstance("SHA1");
> try(var input = Files.newInputStream(Path.of("myfile.txt"));
> var output = new DigestOutputStream(OutputStream.nullOutputStream(), digest)) {
> input.transferTo(output);
> }
> var hash = digest.digest();
>
> or 3 lines if you don't mind to load the whole file in memory
>
> var digest = MessageDigest.getInstance("SHA1");
> digest.update(Files.readAllBytes(Path.of("myfile.txt")));
> var hash = digest.digest();
>
>>
>> Paul.
>
> Rémi
More information about the core-libs-dev
mailing list