java 文件备份完整性校验
时间: 2023-11-12 19:57:45 浏览: 43
Java文件备份完整性校验可以通过计算文件的哈希值来实现。常用的哈希算法有MD5、SHA-1、SHA-256等。具体实现可以使用Java自带的MessageDigest类。
示例代码:
```java
import java.io.*;
import java.security.*;
public class FileIntegrityCheck {
public static void main(String[] args) throws Exception {
String filePath = "test.txt";
String algorithm = "MD5";
String hash = getFileHash(filePath, algorithm);
System.out.println("File hash: " + hash);
}
public static String getFileHash(String filePath, String algorithm) throws Exception {
MessageDigest md = MessageDigest.getInstance(algorithm);
try (InputStream is = new FileInputStream(filePath)) {
byte[] buffer = new byte[8192];
int read;
while ((read = is.read(buffer)) > 0) {
md.update(buffer, 0, read);
}
}
byte[] hashBytes = md.digest();
StringBuilder sb = new StringBuilder();
for (byte b : hashBytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}
```