• Android检验下载的文件的完整性


    在应用开发中往往需要将下载成功的文件进行MD5校验,就是获取一个文件的消息摘要,每个文件生成的摘要都是独一无二的,生成的消息摘要是128位(16个字节)的数据,一般都需要将他们转换成十六进制的字符串。将十进制数转换成十六进制可以使用Integer.toHexString(int num),只要低八位可以使用0xff & num就只会截取32位的整型数值的低八位。

    测试程序:

    MessageDigest degest = MessageDigest.getInstance("MD5");
    FileInputStream inputStream=new FileInputStream("test.txt");
    DigestInputStream dis=new DigestInputStream(inputStream, degest);//对于大文件或者网络文件使用输入流的形式要比字节数组方便很多也节省内存
    byte[] buffer=new byte[8986];
    ByteArrayOutputStream fileOutput=new ByteArrayOutputStream();
    while((dis.read(buffer))!=-1){
    //跟读普通输入流是一样的,原理就是需要将输入流读完后,再调用digest方法才能获取整个文件的MD5
      
    fileOutput.write(buffer);
    }
    String fileContent=fileOutput.toString();//读取到的文件的内容
    byte[] sumary=degest.digest();
    StringBuffer strBuffer = new StringBuffer();
    for (int i = 0; i < sumary.length; i++) {
      String tmp=Integer.toHexString(sumary[i]&0xff);
      if(tmp.length()==1)//如果这个字节的值小于16,那么转换的就只有一个字符,所以需要手动添加一个字符“0”,
        tmp="0"+tmp; strBuffer.append(tmp
    ); } System.out.println(strBuffer.toString());
  • 相关阅读:
    带编译器的codeblocks下载地址
    联想拯救者s15k重装w10系统教程
    w10下Oracle 11g完全干净卸载
    小机房的树(codevs 2370)
    NOIP[2015] 运输计划(codevs 4632)
    ⑨要写信(codevs 1697)
    酒厂选址(codevs 1507)
    美丽的大树(codevs 2124)
    乘法运算(codevs 3254)
    货车运输(codevs 3287)
  • 原文地址:https://www.cnblogs.com/xushihai/p/4619589.html
Copyright © 2020-2023  润新知