需求:
- 文件上传的同时计算 hash 值
- 输入流使用是计算 hash
实现:
上面两个需求其实都是一致的 都是 处理 InputStream 同时计算 Hash 值
我们知道 Java IO 是使用的 装饰模式, 那么我们只需要对 BufferedInputStream 进行封装即可
重点是 Override public int read(final byte[] anB) throws IOException
这样仅支持连续完整的使用 public int read(final byte[] anB) throws IOException 读取完 流的情况,所以还是有很大局限性。
package me.vanlin.test; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashSet; import java.util.Set; import org.apache.commons.io.IOUtils; /** * @author liuwl * */ public class HashBufferedInputStream extends BufferedInputStream { private final MessageDigest messageDigest; private static final Set<String> algorithms = new HashSet<>(); static { algorithms.add("MD5"); algorithms.add("SHA-1"); algorithms.add("SHA-256"); algorithms.add("SHA-512"); } /** * @param anIn * @throws NoSuchAlgorithmException */ public HashBufferedInputStream(final InputStream anIn, final String algorithm) throws NoSuchAlgorithmException { super(anIn); if (!algorithms.contains(algorithm)) { throw new RuntimeException("algorithm not support"); } messageDigest = MessageDigest.getInstance(algorithm); } /** * @param anIn * @param anSize * @throws NoSuchAlgorithmException */ public HashBufferedInputStream(final InputStream anIn, final int anSize, final String algorithm) throws NoSuchAlgorithmException { super(anIn, anSize); if (!algorithms.contains(algorithm)) { throw new RuntimeException("algorithm not support"); } messageDigest = MessageDigest.getInstance(algorithm); } @Override public int read(final byte[] anB) throws IOException { final int result = super.read(anB); if (result != -1) { messageDigest.update(anB, 0, result); } return result; } public String getHash() { final byte byteBuffer[] = messageDigest.digest(); final StringBuffer hexStr = new StringBuffer(); for (final byte element : byteBuffer) { final String hex = Integer.toHexString(0xff & element); if (hex.length() == 1) { hexStr.append('0'); } hexStr.append(hex); } return hexStr.toString(); } public static void main(final String[] args) throws NoSuchAlgorithmException, IOException { final File file = new File("E:\\me\\front-end.tar.gz"); try (final FileInputStream inputStream = new FileInputStream(file); final HashBufferedInputStream hashBufferedInputStream = new HashBufferedInputStream(inputStream, "MD5"); final FileOutputStream outputStream = new FileOutputStream("E://me//testtesttest.tar.gz"); final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);) { IOUtils.copy(hashBufferedInputStream, bufferedOutputStream); System.out.println(hashBufferedInputStream.getHash()); } } }
代码如有纰漏请不吝赐教。
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于