Iker Jimenez
Iker Jimenez

Reputation: 7245

How to get the md5sum of a file in Java?

I have a file that I need to reload in my application everytime it changes.

I'm checking its lastModified and I'd also like to check its md5sum before I process it.

I'm using Spring framework, in case there is something useful in there.

What's the best way to check this? Any examples/libraries that I should check?

Thanks.

Upvotes: 0

Views: 3672

Answers (5)

cb0
cb0

Reputation: 8613

Use the MessageDigest class, you can find a good example here.

Upvotes: 0

Ahmed Kotb
Ahmed Kotb

Reputation: 6307

the explanation and code snippet in this link might help you

just for the record , there is a common issue in most of snippets that use bigInteger , the bigInteger class removes extra zeros at the start of the string so you might want to add a check like that

    String res =new BigInteger(1,m.digest()).toString(16);
    if (res.length() == 31)
          res = "0" + res;

Upvotes: 2

Kevin
Kevin

Reputation: 4727

You can do it with Java builtin functions:

MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(...your data here...);
byte[] hash = digest.digest();

or try another implementation here, certainly faster (according to it's name :)

EDIT :

they seem to provide file md5sum, exactly what you want !

You want the extra convenience methods for hashing a file...

String hash = MD5.asHex(MD5.getHash(new File(filename)));

Upvotes: 0

Sigman
Sigman

Reputation: 11

    InputStream in = new FileInputStream(filename);

    MessageDigest md5 = MessageDigest.getInstance("MD5");
    byte[] buffer = new byte[1024];

    while (true)
    {
        int c = in.read(buffer);

        if (c > 0)
            md5.update(buffer, 0, c);
        else if (c < 0)
            break;
    }

    in.close();

    byte[] result = md5.digest();

Upvotes: 1

Matthew
Matthew

Reputation: 1875

You'd have to read in the entire file and feed it to an instance of MessageDigest.

Upvotes: 0

Related Questions