Java/Android 大文件获取SHA1防止内存溢出

    在Java或者Android开发中难免要遇到校验文件正确性的问题。比如下载一个apk包或者下载一个游戏包,担心文件会被篡改。这个时候就可以对比源文件的SHA1和下载到本地的文件的SHA1。

    在这个过程中往往会遇到文件比较大,读取很慢或者一次性读取造成内存溢出的问题。我们下面结合代码来讲解和解决这个问题。


/**
* 大文件获取 SHA1  防止内存溢出
* @param file
* @return
*/
public static String getSHA1Value(File file){
StringBuilder builder = new StringBuilder();
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
MappedByteBuffer mappedByteBuffer = null;
long bufferSize = 1024*1024*2;//每2M 读取一次,防止内存溢出
long fileLength = file.length();//文件大小
long lastBuffer = fileLength%bufferSize;//文件最后不足2M 的部分
long bufferCount = fileLength/bufferSize;//
for(int b = 0; b < bufferCount; b++){//分块映射
mappedByteBuffer = fileInputStream.getChannel().map(FileChannel.MapMode.READ_ONLY, b*bufferSize, bufferSize);//使用内存映射而不是直接用IO读取文件,加快读取速度
messageDigest.update(mappedByteBuffer);
}
if(lastBuffer != 0){
mappedByteBuffer = fileInputStream.getChannel().map(FileChannel.MapMode.READ_ONLY, bufferCount*bufferSize, lastBuffer);
messageDigest.update(mappedByteBuffer);
}
byte[] digest =messageDigest.digest();
String hexString = "";
for(int i =0; i < digest.length; i ++){
hexString = Integer.toHexString(digest[i]&0xFF);//转16进制数,再转成哈希码
if(hexString.length()<2){
builder.append(0);
}
builder.append(hexString);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
fileInputStream.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return builder.toString();
}

这样,就可以快速的读取大文件,而且不会造成内存溢出。 

发布了63 篇原创文章 · 获赞 41 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/MarketAndTechnology/article/details/80618539