简体   繁体   English

如何在互联网上阅读和计算文件的哈希值

[英]How to read and calculate hash of file on the internet

I have a url of a file on the Internet. 我在互联网上有一个文件的URL。 I need to calculate the SHA1 hash, and read this file by each line. 我需要计算SHA1哈希值,并按每行读取此文件。 I know how to do this, but I read this file twice which probably isn't a very good solution. 我知道怎么做,但我读了两次这个文件,这可能不是一个很好的解决方案。

How can I do this more effectively? 我怎样才能更有效地做到这一点?

Here is my code: 这是我的代码:

URL url = new URL(url);
URLConnection urlConnection = url.openConnection();
urlConnection.setConnectTimeout(1000);
urlConnection.setReadTimeout(1000);
logger.error(urlConnection.getContent() + " ");
InputStream is = urlConnection.getInputStream();


// first reading of file is:

int i;
File file = new File("nameOfFile");
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = 
           new BufferedOutputStream(new FileOutputStream(file.getName()));
while ((i = bis.read()) != -1) {
    bos.write(i);
}
bos.flush();
bis.close();   
sha1(file);

// second reading of file is:

BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;

while ((line = reader.readLine()) != null) {
   // do something
}

protected byte[] sha1(final File file) throws Exception {
    if (file == null || !file.exists()) {
        return null;
    }
    final MessageDigest messageDigest = MessageDigest.getInstance(SHA1);

    InputStream is = new BufferedInputStream(new FileInputStream(file));
    try {
        final byte[] buffer = new byte[1024];
        for (int read = 0; (read = is.read(buffer)) != -1;) {
            messageDigest.update(buffer, 0, read);
        }
    } finally {
        IOUtils.closeQuietly(is);
    }
    return messageDigest.digest();
}

If you pass it through a DigestInputStream , it'll do the MessageDigest and still be usable as an InputStream . 如果你通过DigestInputStream传递它,它将执行MessageDigest并仍可用作InputStream

DigestInputStream dis = new DigestInputStream(is,
  MessageDigest.getInstance(SHA1));
BufferedInputStream bis = new BufferedInputStream(dis);
BufferedOutputStream bos = new BufferedOutputStream(
  new FileOutputStream(file.getName()));
while ((i = bis.read()) != -1) {
   bos.write(i);
}
bos.close();
return dis.getMessageDigest().digest();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM