首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FileChannel ByteBuffer和哈希文件

FileChannel ByteBuffer和哈希文件
EN

Stack Overflow用户
提问于 2013-04-17 11:15:30
回答 3查看 4.3K关注 0票数 6

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

因为这个方法是我正在工作的项目中不可或缺的一部分,所以我正在努力寻找每一个性能的最后一滴。有人建议我尝试使用FileChannel而不是常规的FileInputStream

我最初的方法是:

代码语言:javascript
复制
    /**
     * 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);
        }
    }

重构方法:

代码语言:javascript
复制
    /**
     * 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扔过去测试了。

使用now current方法更新UPDATE:

代码语言:javascript
复制
    /**
     * 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.92 my文件的MD5。当然,任何基准测试都是相对的,因为有操作系统和磁盘缓存以及其他“魔术”在进行,它们会扭曲对相同文件的重复读取……但这里有一些基准测试。我加载了每个方法,并在重新编译后启动了5次。基准测试取自上一次(第5次)运行,因为这将是该算法的“最热”运行,以及任何“魔法”(无论如何在我的理论中)。

代码语言:javascript
复制
Here's the benchmarks so far: 

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

这是散列相同的2.92 to文件所需的25.03% decrease时间。相当不错。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-04-17 12:11:19

3个建议:

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

代码语言:javascript
复制
while (fc.read(bbf) != -1) {
    md.update(bbf.array(), 0, bytes);
    bbf.clear();
}

2)不要同时关闭fc和fis,这是多余的,关闭fis就足够了。FileInputStream.close接口如下所示:

代码语言:javascript
复制
If this stream has an associated channel then the channel is closed as well.

3)如果您希望使用FileChannel提高性能,请使用

代码语言:javascript
复制
ByteBuffer.allocateDirect(1024); 
票数 3
EN

Stack Overflow用户

发布于 2014-04-02 04:15:56

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

例如:

代码语言:javascript
复制
        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);
        }

附录

注意:字符串构建代码中有一个bug。它将零打印为一位数。这个问题很容易解决。例如:

代码语言:javascript
复制
hexString.append(mdbytes[i] == 0 ? "00" : Integer.toHexString((0xFF & mdbytes[i])));

此外,作为实验,我重写了代码以使用映射的字节缓冲区。它的运行速度大约快了30% (6-7毫升v.9-11毫升FWIW)。如果您编写的代码散列代码直接在字节缓冲区上操作,我希望您可以从中获得更多好处。

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

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

代码语言:javascript
复制
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();
        }
    }
}
票数 1
EN

Stack Overflow用户

发布于 2013-10-07 05:40:36

以下是使用NIO进行文件散列的示例

  • Path
  • FileChanngel
  • MappedByteBuffer

并避免使用byte[]。因此,我认为这应该是上面的改进版本。以及第二个nio示例,其中散列值存储在用户属性中。即可用于生成HTML etag的其他示例文件不会发生变化。

代码语言:javascript
复制
    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;
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16050827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档