Integration test for image download java

坚强是说给别人听的谎言 提交于 2019-12-04 20:50:17

Comparing the images' hash value will be helpful.

  1. Compute the hash value before and after downloading the file.
  2. Compare the hash values. If they are equal, your file's integrity is good.

You can use hash algorithms like MD5 or SHA-1. If the files are smaller MD5 is good. For large number of file comparison SHA-1 will be useful since there will be less collisions.

ekostadinov

Since you are using and

expect to get the file in byte[]

There's an input stream decorator, java.security.DigestInputStream or java.security.MessageDigest, so that you can compute the digest while using the input stream.

import java.io.*;
import java.security.MessageDigest;

public class MD5Checksum {

   public static byte[] createChecksum(String filename) throws Exception {
       InputStream fis =  new FileInputStream(filename);

       byte[] buffer = new byte[1024];
       MessageDigest complete = MessageDigest.getInstance("MD5");
       int numRead;

       do {
           numRead = fis.read(buffer);
           if (numRead > 0) {
               complete.update(buffer, 0, numRead);
           }
       } while (numRead != -1);

       fis.close();
       return complete.digest();
   }

   public static String getMD5Checksum(String filename) throws Exception {
       byte[] b = createChecksum(filename);
       String result = "";

       for (int i=0; i < b.length; i++) {
           result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
       }
       return result;
   }

   public static void main(String args[]) {
       try {
           System.out.println(getMD5Checksum("apache-tomcat-5.5.17.exe"));               
       }
       catch (Exception e) {
           e.printStackTrace();
       }
   }
}

Here you can find other also good code snippets.

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