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

独自空忆成欢 提交于 2019-12-22 01:43:39

问题


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.


回答1:


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();


来源:https://stackoverflow.com/questions/10795749/how-to-generate-a-md5-checksum-for-a-csv-file-in-jsp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!