在Java中,可以使用以下四种方法来获取文件的MD5值:
import java.io.FileInputStream;
import java.security.MessageDigest;
public class FileMD5 {
public static void main(String[] args) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
FileInputStream fis = new FileInputStream("path/to/file");
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
}
byte[] mdbytes = md.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++) {
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
System.out.println("MD5: " + sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
import org.apache.commons.codec.digest.DigestUtils;
import java.io.FileInputStream;
import java.io.IOException;
public class FileMD5 {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("path/to/file");
String md5 = DigestUtils.md5Hex(fis);
System.out.println("MD5: " + md5);
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
public class FileMD5 {
public static void main(String[] args) {
try {
Path path = Paths.get("path/to/file");
byte[] dataBytes = Files.readAllBytes(path);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] mdbytes = md.digest(dataBytes);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++) {
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
System.out.println("MD5: " + sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用Guava:
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
public class FileMD5 {
public static void main(String[] args) {
try {
File file = new File("path/to/file");
HashCode md5 = Files.hash(file, Hashing.md5());
System.out.println("MD5: " + md5.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用Apache Commons IO:
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class FileMD5 {
public static void main(String[] args) {
try {
File file = new File("path/to/file");
String md5 = DigestUtils.md5Hex(FileUtils.readFileToByteArray(file));
System.out.println("MD5: " + md5);
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上是在Java中获取文件的MD5值的四种方法。可以根据实际情况选择合适的方法来使用。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: java构造方法重载的概念是什么