由於項目中需要使用文件做備份,並且要提供備份文件的下載功能。備份文件體積較大,為確保下載后的文件與原文件一致,需要提供文件完整性校驗。
網上有這么多此類文章,其中不少使用到了
org.apache.commons.codec.digest.DigestUtils
包中的方法,但是又自己做了大文件的拆分及獲取相應校驗碼的轉換。
DigestUtils 包已經提供了為文件流生成校驗碼的功能,可以直接調用。經測試10幾G的文件在30秒內可完成計算。
(網上提供的一些自己拆分大文件的示例,文件較小時結果正確,文件較大時結果就不太可靠了)
實現步驟如下:
- pom.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); } }
