【问题标题】:FileChannel ByteBuffer and Hashing FilesFileChannel ByteBuffer 和散列文件
【发布时间】:2013-04-17 03:15:29
【问题描述】:

我在 java 中构建了一个文件散列方法,它接受 filepath+filename 的输入字符串表示,然后计算该文件的散列。哈希可以是任何本机支持的 ​​Java 哈希算法,例如 MD2SHA-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);
        }
    }

重构方法:

    /**
     * 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);
        }
    }

两者都返回正确的哈希值,但是重构的方法似乎只在小文件上合作。当我传入一个大文件时,它完全窒息而我不知道为什么。我是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);
        }
    }

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

Here's the benchmarks so far: 

    Original Method - 14.987909 (s) 
    Latest Method - 11.236802 (s)

这是一个 25.03% decrease 哈希同一个 2.92GB 文件的时间。挺好的。

【问题讨论】:

  • 为什么不使用直接采用ByteBufferMessageDigest.update(ByteBuffer) 方法而不是使用后备数组?
  • 只是想为未来的访问者添加 - 如果您切换到使用 ByteBuffer.allocateDirect() 则没有后备数组,ByteBuffer.array()fail。而是根据@prunge 建议切换到使用MessageDigest.update(ByteBuffer)。这不仅比尝试将缓冲区读取到某个数组然后将该数组传递给MessageDigest.update() 更有效,而且更干净。
  • @SnakeDoc 我在您的哈希数字的字符串化代码中发现了一个错误。还提出了一个内存映射实现,它可以通过在文件上以小于 2GB 的增量多次映射来适应更大的文件。
  • 我认为这是不正确的:Integer.toHexString((0xFF & mdbytes[i])) 前导零将被丢弃为 0x00-0x0F
  • 该代码没有产生有效的哈希码。实际上,前导零被丢弃了。应该使用String.format("%02x", mdbytes[i]) 而不是Integer.toHexString(0xFF &amp; mdbytes[i]) 来避免这种情况。

标签: java file hash


【解决方案1】:

3 条建议:

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

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

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

If this stream has an associated channel then the channel is closed as well.

3) 如果您想通过 FileChannel 提高性能,请使用

ByteBuffer.allocateDirect(1024); 

【讨论】:

  • 如果使用ByteBuffer.allocateDirect(1024);,则ByteBuffer.array() 调用将失败并显示UnsupportedOperationException
  • @prunge 我遇到了一点麻烦...我想我在最新的更新中解决了这个问题...现在看起来怎么样?
  • 可以,但是你可以使用 ByteBuffer.get(byte[])
  • (4) 使用更大的缓冲区。 1024 太小了,大约从 1996 年开始使用。至少使用 4096,最好更像 64k。
  • 我想你已经找到了你需要的东西。我对 8192 作为缓冲区大小没有任何问题,我同意它可以太大也可以太小。理想的大小可能是磁盘集群大小,但据我所知,您无法从 Java 中获得它。我看不出为什么在这里使用直接缓冲区是个好主意。仅当您只是复制数据而不在 Java 代码中查看它时,它才有用。使用 get() 否定了直接缓冲区的所有优点。
【解决方案2】:

如果代码只分配一次临时缓冲区,则可能会出现另一个可能的改进。

例如

        int bufsize = 8192;
        ByteBuffer buffer = ByteBuffer.allocateDirect(bufsize); 
        byte[] temp = new byte[bufsize];
        int b = channel.read(buffer);

        while (b > 0) {
            buffer.flip();

            buffer.get(temp, 0, b);
            md.update(temp, 0, b);
            buffer.clear();

            b = channel.read(buffer);
        }

附录

注意:字符串构建代码中存在错误。它将零打印为单个数字。这很容易解决。例如

hexString.append(mdbytes[i] == 0 ? "00" : Integer.toHexString((0xFF & mdbytes[i])));

另外,作为一个实验,我重写了代码以使用映射字节缓冲区。它的运行速度提高了大约 30%(6-7 毫秒对 9-11 毫秒 FWIW)。如果您编写直接在字节缓冲区上操作的代码哈希代码,我希望您可以从中获得更多收益。

我试图通过在启动计时器之前使用每个算法对 不同 文件进行散列来计算 JVM 初始化和文件系统缓存。第一次运行代码比正常运行慢约 25 倍。这似乎是由于 JVM 初始化造成的,因为计时循环中的所有运行的长度大致相同。它们似乎没有从缓存中受益。我用MD5算法测试过。此外,在计时部分,在测试程序期间只运行一种算法。

循环中的代码更短,因此可能更容易理解。我不能 100% 确定大量文件在 JVM 上会产生什么样的压力内存映射,所以如果你想运行,你可能需要研究和考虑这种解决方案这在负载下。

public static byte[] hash(File file, String hashAlgo) throws IOException {

    FileInputStream inputStream = null;

    try {
        MessageDigest md = MessageDigest.getInstance(hashAlgo);
        inputStream = new FileInputStream(file);
        FileChannel channel = inputStream.getChannel();

        long length = file.length();
        if(length > Integer.MAX_VALUE) {
            // you could make this work with some care,
            // but this code does not bother.
            throw new IOException("File "+file.getAbsolutePath()+" is too large.");
        }

        ByteBuffer buffer = channel.map(MapMode.READ_ONLY, 0, length);

        int bufsize = 1024 * 8;          
        byte[] temp = new byte[bufsize];
        int bytesRead = 0;

        while (bytesRead < length) {
            int numBytes = (int)length - bytesRead >= bufsize ? 
                                         bufsize : 
                                         (int)length - bytesRead;
            buffer.get(temp, 0, numBytes);
            md.update(temp, 0, numBytes);
            bytesRead += numBytes;
        }

        byte[] mdbytes = md.digest();
        return mdbytes;

    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Unsupported Hash Algorithm.", e);
    }
    finally {
        if(inputStream != null) {
            inputStream.close();
        }
    }
}

【讨论】:

    【解决方案3】:

    这是一个使用 NIO 进行文件散列的示例

    • 路径
    • 文件通道
    • 映射字节缓冲区

    并避免使用 byte[]。所以我认为这应该是上述的改进版本。 第二个 nio 示例,其中哈希值存储在用户属性中。那 可用于 HTML etag 生成,其他示例文件不会更改。

        public static final byte[] getFileHash(final File src, final String hashAlgo) throws IOException, NoSuchAlgorithmException {
        final int         BUFFER = 32 * 1024;
        final Path        file = src.toPath();
        try(final FileChannel fc   = FileChannel.open(file)) {
            final long        size = fc.size();
            final MessageDigest hash = MessageDigest.getInstance(hashAlgo);
            long position = 0;
            while(position < size) {
                final MappedByteBuffer data = fc.map(FileChannel.MapMode.READ_ONLY, 0, Math.min(size, BUFFER));
                if(!data.isLoaded()) data.load();
                System.out.println("POS:"+position);
                hash.update(data);
                position += data.limit();
                if(position >= size) break;
            }
            return hash.digest();
        }
    }
    
    public static final byte[] getCachedFileHash(final File src, final String hashAlgo) throws NoSuchAlgorithmException, FileNotFoundException, IOException{
        final Path path = src.toPath();
        if(!Files.isReadable(path)) return null;
        final UserDefinedFileAttributeView view = Files.getFileAttributeView(path, UserDefinedFileAttributeView.class);
        final String name = "user.hash."+hashAlgo;
        final ByteBuffer bb = ByteBuffer.allocate(64);
        try { view.read(name, bb); return ((ByteBuffer)bb.flip()).array();
        } catch(final NoSuchFileException t) { // Not yet calculated
        } catch(final Throwable t) { t.printStackTrace(); }
        System.out.println("Hash not found calculation");
        final byte[] hash = getFileHash(src, hashAlgo);
        view.write(name, ByteBuffer.wrap(hash));
        return hash;
    }
    

    【讨论】:

    • 您应该映射整个文件一次,而不是所有这些位。您似乎没有意识到与使用大量映射缓冲区相关的内存/收集问题。
    • @EJP 为了完整性,您能否详细说明或链接为什么它在这种情况下可能不好?
    • 1) 一次将大文件映射到内存没有问题吗? 2)有没有办法“移动”映射窗口?
    猜你喜欢
    • 2019-11-23
    • 2012-12-24
    • 1970-01-01
    • 2010-09-10
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    相关资源
    最近更新 更多