我编写了以下程序来计算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对象一次调用即可读取整个文件。