<分区>
我编写了以下程序来计算 Java 中字符串的 SHA-256 哈希值:
public class ToHash {
public static void main(String[] args) {
byte[] data = "test".getBytes("UTF8");
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(data);
System.out.println(new BASE64Encoder().encode(hash));
}
}
嗯,这很好用。在下一步中,我想以一种接受文件并计算其哈希值的方式开发它。我的解决方案是读取字符串数组中的整个文件,然后对该字符串数组调用 digest()
方法。但是有两个问题:
我不知道如何将整个文件读入数组?目前我认为我必须逐行阅读它并用新行附加一个数组!
以上方法对于大文件需要大量内存!
这是我当前读取文件的程序:
public class ToHash {
public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, FileNotFoundException, IOException {
// TODO code application logic here
// The name of the file to open.
String fileName = "C:\\Users\\ghasemi\\Desktop\\1.png";
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(fileName));
while ((sCurrentLine = br.readLine()) != null) {
byte[] data = sCurrentLine.getBytes("UTF8");
System.out.println(new BASE64Encoder().encode(data));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
BufferedReader
对象似乎没有一次调用读取整个文件的方法。