FileChannel ByteBuffer和Hashing Files

Sna*_*Doc 5 java hash file

我在java中构建了一个文件哈希方法,它接受a的输入字符串表示,filepath+filename然后计算该文件的哈希值.散列可以是任何本机支持的java散列算法,例如MD2through SHA-512.

我试图找出最后一滴性能,因为这个方法是我正在研究的项目的一个组成部分.我被建议尝试使用FileChannel而不是常规FileInputStream.

我原来的方法:

    /**
     * Gets Hash of file.
     * 
     * @param file String path + filename of file to get hash.
     * @param hashAlgo Hash algorithm to use. <br/>
     *     Supported algorithms are: <br/>
     *     MD2, MD5 <br/>
     *     SHA-1 <br/>
     *     SHA-256, SHA-384, SHA-512
     * @return String value of hash. (Variable length dependent on hash algorithm used)
     * @throws IOException If file is invalid.
     * @throws HashTypeException If no supported or valid hash algorithm was found.
     */
    public String getHash(String file, String hashAlgo) throws IOException, HashTypeException {
        StringBuffer hexString = null;
        try {
            MessageDigest md = MessageDigest.getInstance(validateHashType(hashAlgo));
            FileInputStream fis = new FileInputStream(file);

            byte[] dataBytes = new byte[1024];

            int nread = 0;
            while ((nread = fis.read(dataBytes)) != -1) {
                md.update(dataBytes, 0, nread);
            }
            fis.close();
            byte[] mdbytes = md.digest();

            hexString = new StringBuffer();
            for (int i = 0; i < mdbytes.length; i++) {
                hexString.append(Integer.toHexString((0xFF & mdbytes[i])));
            }

            return hexString.toString();

        } catch (NoSuchAlgorithmException | HashTypeException e) {
            throw new HashTypeException("Unsuppored Hash Algorithm.", e);
        }
    }
Run Code Online (Sandbox Code Playgroud)

重构方法:

    /**
     * Gets Hash of file.
     * 
     * @param file String path + filename of file to get hash.
     * @param hashAlgo Hash algorithm to use. <br/>
     *     Supported algorithms are: <br/>
     *     MD2, MD5 <br/>
     *     SHA-1 <br/>
     *     SHA-256, SHA-384, SHA-512
     * @return String value of hash. (Variable length dependent on hash algorithm used)
     * @throws IOException If file is invalid.
     * @throws HashTypeException If no supported or valid hash algorithm was found.
     */
    public String getHash(String fileStr, String hashAlgo) throws IOException, HasherException {

        File file = new File(fileStr);

        MessageDigest md = null;
        FileInputStream fis = null;
        FileChannel fc = null;
        ByteBuffer bbf = null;
        StringBuilder hexString = null;

        try {
            md = MessageDigest.getInstance(hashAlgo);
            fis = new FileInputStream(file);
            fc = fis.getChannel();
            bbf = ByteBuffer.allocate(1024); // allocation in bytes

            int bytes;

            while ((bytes = fc.read(bbf)) != -1) {
                md.update(bbf.array(), 0, bytes);
            }

            fc.close();
            fis.close();

            byte[] mdbytes = md.digest();

            hexString = new StringBuilder();

            for (int i = 0; i < mdbytes.length; i++) {
                hexString.append(Integer.toHexString((0xFF & mdbytes[i])));
            }

            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            throw new HasherException("Unsupported Hash Algorithm.", e);
        }
    }
Run Code Online (Sandbox Code Playgroud)

两者都返回正确的哈希值,但重构的方法似乎只对小文件合作.当我传入一个大文件时,它完全窒息而我无法弄清楚原因.我是新手,NIO所以请指教.

编辑:忘了提到我正在通过它投掷SHA-512进行测试.

UPDATE: 使用我现在的方法更新.

    /**
     * Gets Hash of file.
     * 
     * @param file String path + filename of file to get hash.
     * @param hashAlgo Hash algorithm to use. <br/>
     *     Supported algorithms are: <br/>
     *     MD2, MD5 <br/>
     *     SHA-1 <br/>
     *     SHA-256, SHA-384, SHA-512
     * @return String value of hash. (Variable length dependent on hash algorithm used)
     * @throws IOException If file is invalid.
     * @throws HashTypeException If no supported or valid hash algorithm was found.
     */
    public String getHash(String fileStr, String hashAlgo) throws IOException, HasherException {

        File file = new File(fileStr);

        MessageDigest md = null;
        FileInputStream fis = null;
        FileChannel fc = null;
        ByteBuffer bbf = null;
        StringBuilder hexString = null;

        try {
            md = MessageDigest.getInstance(hashAlgo);
            fis = new FileInputStream(file);
            fc = fis.getChannel();
            bbf = ByteBuffer.allocateDirect(8192); // allocation in bytes - 1024, 2048, 4096, 8192

            int b;

            b = fc.read(bbf);

            while ((b != -1) && (b != 0)) {
                bbf.flip();

                byte[] bytes = new byte[b];
                bbf.get(bytes);

                md.update(bytes, 0, b);

                bbf.clear();
                b = fc.read(bbf);
            }

            fis.close();

            byte[] mdbytes = md.digest();

            hexString = new StringBuilder();

            for (int i = 0; i < mdbytes.length; i++) {
                hexString.append(Integer.toHexString((0xFF & mdbytes[i])));
            }

            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            throw new HasherException("Unsupported Hash Algorithm.", e);
        }
    }
Run Code Online (Sandbox Code Playgroud)

所以我尝试使用我的原始示例和我最新的更新示例,对2.92GB文件的MD5进行基准测试.当然,任何基准测试都是相对的,因为存在操作系统和磁盘缓存以及其他会导致重复读取相同文件的"魔法"......但这里有一些基准测试.我把每个方法加载起来并在将它编译为新鲜后将其关闭5次.基准测试取自最后一次(第5次),因为这将是该算法的"最热门"运行,以及任何"魔术"(在我的理论中无论如何).

Here's the benchmarks so far: 

    Original Method - 14.987909 (s) 
    Latest Method - 11.236802 (s)
Run Code Online (Sandbox Code Playgroud)

这是25.03% decrease用于散列相同的2.92GB文件的时间.非常好.

Evg*_*eev 3

3条建议:

1)每次读取后清除缓冲区

while (fc.read(bbf) != -1) {
    md.update(bbf.array(), 0, bytes);
    bbf.clear();
}
Run Code Online (Sandbox Code Playgroud)

2)不要同时关闭fc和fis,这是多余的,关闭fis就足够了。FileInputStream.close API 说:

If this stream has an associated channel then the channel is closed as well.
Run Code Online (Sandbox Code Playgroud)

3) 如果你想通过 FileChannel 使用来提高性能

ByteBuffer.allocateDirect(1024); 
Run Code Online (Sandbox Code Playgroud)

  • (4) 使用更大的缓冲区。1024 太小了,大约从 1996 年开始就这样了。至少使用 4096,最好更像 64k。 (2认同)
  • 我想你已经找到了你需要的东西。我对 8192 作为缓冲区大小没有任何问题,并且我同意它可以太大也可以太小。理想的大小可能是磁盘簇大小,但据我所知,您无法从 Java 获得该大小。我不明白为什么使用直接缓冲区是一个好主意。仅当您只是复制数据而不在 Java 代码中查看它时,它才有用。使用 get() 否定了直接缓冲区的所有优点。 (2认同)