Search code examples
jspcsvmd5checksum

How to generate a md5 checksum for a CSV file in JSP


I need to calculate the checksum of a csv file. The checksum will change every time the data in the file is changed. I found nothing useful over the internet in this regard.


Solution

  • First of all, this problem is not specific to JSP. JSP is just a HTML code generator. Writing Java code in a JSP file instead of a normal Java class doesn't make it a JSP problem. You would help yourself more if you concentrate on solving future Java problems using the "Java" keyword, not using the "JSP" keyword.

    Said that, you can just use MessageDigest which you update with the bytes read from the file.

    FileInputStream input = new FileInputStream("/path/to/file.csv");
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    byte[] buffer = new byte[10240];
    
    for (int length = 0; (length = input.read(buffer)) > 0;) {
        md5.update(buffer, 0, length);
    }     
    
    byte[] hash = digest.digest();
    

    You may want to convert the hash to hex afterwards.

    StringBuilder hex = new StringBuilder(hash.length * 2);
    
    for (byte b : hash) {
        if ((b & 0xff) < 0x10) {
            hex.append("0");
        }
    
        hex.append(Integer.toHexString(b & 0xff));
    }
    
    String hexString = hex.toString();