我注意到當我在文件上使用readFully()
而不是讀取(byte [])時,處理時間大大減少。然而,讀到富利可能是一把雙刃劍。如果我偶然試圖讀取一個巨大的,多GB的文件,它可能會窒息?ReadFully()有窒息的危險嗎?
下面是一個功能,我使用生成的SHA-256校驗:如果我改用
public static byte[] createChecksum(File log, String type) throws Exception {
DataInputStream fis = new DataInputStream(new FileInputStream(log));
Long len = log.length();
byte[] buffer = new byte[len.intValue()];
fis.readFully(buffer); // TODO: readFully may come at the risk of
// choking on a huge file.
fis.close();
MessageDigest complete = MessageDigest.getInstance(type);
complete.update(buffer);
return complete.digest();
}
:
DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(log)));
將是allieviate這種風險?或者...是最好的選擇(在無法使用數據大小的情況下)始終控制讀入的字節數並使用循環直到讀取所有字節爲止? (想想吧,由於MessageDigest API一次接受完整的字節數組,我不確定如何獲得校驗和而不是立即填充所有數據,但我想這是另一個問題爲另一個線程
您正在使用的'update()'方法不需要所有的數據。您可以在每個摘要中多次調用它。 – erickson