因为项目中须要使用文件作备份,而且要提供备份文件的下载功能。备份文件体积较大,为确保下载后的文件与原文件一致,须要提供文件完整性校验。java
网上有这么多此类文章,其中很多使用到了apache
org.apache.commons.codec.digest.DigestUtils
包中的方法,可是又本身作了大文件的拆分及获取相应校验码的转换。测试
DigestUtils 包已经提供了为文件流生成校验码的功能,能够直接调用。经测试10几G的文件在30秒内可完成计算。spa
(网上提供的一些本身拆分大文件的示例,文件较小时结果正确,文件较大时结果就不太可靠了)code
实现步骤以下:xml
<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.12</version> </dependency>
package file.integrity.check; import org.apache.commons.codec.digest.DigestUtils; import java.io.File; import java.io.FileInputStream; public class Application { public static void main(String[] args) throws Exception { File file = new File("/path/filename"); FileInputStream fileInputStream = new FileInputStream(file); String hex = DigestUtils.sha512Hex(fileInputStream); System.out.println(hex); } }
import org.apache.commons.codec.digest.DigestUtils; import static org.apache.commons.codec.digest.MessageDigestAlgorithms.SHA_512; import java.io.File; public class Application { public static void main(String[] args) throws Exception { File file = new File("/path/filename"); String hex = new DigestUtils(SHA_512).digestAsHex(file); System.out.println(hex); } }