【源码打包】【户外网源码】【资金托管源码】fileutils源码

时间:2024-11-23 13:13:08 来源:注册充值网站源码 编辑:linux 源码安装 步骤

1.如何计算Inputstream的MD5

fileutils源码

如何计算Inputstream的MD5

       é¦–先,最简单的方式就是把你的两行代码结合起来,先保存文件,再读取文件流计算MD5:

       public static String copyInputStreamToFileAndGetMd5Hex(InputStream inputStream,源码打包 File file) throws IOException {

        FileUtils.copyInputStreamToFile(inputStream, file);

        return DigestUtils.md5Hex(new FileInputStream(file));

       }

       å½“然这样做要对同一个流读取两次,显得不够低碳环保。

       æ­¤æ—¶å¯ä»¥çœ‹ä¸‹DigestUtils源码,追其根溯其源可以看到:

        public static MessageDigest updateDigest(final MessageDigest digest, final InputStream data) throws IOException {

        final byte[] buffer = new byte[STREAM_BUFFER_LENGTH];

        int read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);

        while (read > -1) {

        digest.update(buffer, 0, read);

        read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);

        }

        return digest;

        }

       ä¹Ÿä¸æ˜¯å¤šé«˜çº§çš„技术,就是把整个InputStream拆成长度的字节数组逐个MD5。

       å†çœ‹çœ‹FileUtils.copyInputStreamToFile源码的追根溯源实现:

       public static long copyLarge(InputStream input, OutputStream output, byte[] buffer) throws IOException {

        long count;

        int n;

        for(count = 0L; -1 != (n = input.read(buffer)); count += (long)n) {

        output.write(buffer, 0, n);

        }

        return count;

        }

       åŒæ ·ä¹Ÿæ˜¯è®²InputStream拆成的字节数组,逐个写到目标文件中。

       é‚£ä¹ˆï¼Œä¸¤è€…结合起来代码也就好写了:

        public static String copyInputStreamToFileAndGetMd5Hex(InputStream inputStream, File file) throws IOException {

        MessageDigest digest = DigestUtils.getMd5Digest();

        FileOutputStream outputStream = null;

        try {

        outputStream = new FileOutputStream(file);

        byte[] buffer = new byte[];

        int read = inputStream.read(buffer);

        while (read > -1) {

        // 计算MD5,顺便写到文件

        digest.update(buffer, 0, read);

        outputStream.write(buffer, 0, read);

        read = inputStream.read(buffer);

        }

        } finally {

        IOUtils.closeQuietly(outputStream);

        }

        return Hex.encodeHexString(digest.digest());

        }

copyright © 2016 powered by 皮皮网   sitemap