本文主要是介绍Java 枚举类示例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
public enum Hash {
MD5("MD5"), SHA1("SHA1"), SHA256("SHA-256"), SHA512("SHA-512");
private String name;
Hash(String name) {
this.name = name;
}
public String getName() {
return name;
}
public byte[] checksum(File input) {
try (InputStream in = new FileInputStream(input)) {
MessageDigest digest = MessageDigest.getInstance(getName());
byte[] block = new byte[4096];
int length;
while ((length = in.read(block)) > 0) {
digest.update(block, 0, length);
}
return digest.digest();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
import java.io.File;
public class FileChecksumExample {
public static void main(String[] args) throws Exception {
File file = new File("f:\\Fedora-KDE-Live-x86_64-34-1.2.iso");
System.out.println("MD5 : " + toHex(Hash.MD5.checksum(file)));
System.out.println("SHA1 : " + toHex(Hash.SHA1.checksum(file)));
System.out.println("SHA256 : " + toHex(Hash.SHA256.checksum(file)));
System.out.println("SHA512 : " + toHex(Hash.SHA512.checksum(file)));
}
private static String toHex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte aByte : bytes) {
result.append(String.format("%02x", aByte));
// upper case
// result.append(String.format("%02X", aByte));
}
return result.toString();
}
}
这篇关于Java 枚举类示例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!