[英]Verify file is copied in Java
我正在努力將一些文件移動到我項目中的不同目錄,並且它工作得很好,除了我無法驗證它是否正確移動的事實。
我想驗證副本的長度是否與原始相同,然后我想刪除原始。 在我進行驗證之前,我正在關閉兩個FileStream,但由於尺寸不同,它仍然會失敗。 以下是關閉流,驗證和刪除的代碼。
in.close();
out.close();
if (encCopyFile.exists() && encCopyFile.length() == encryptedFile.length())
encryptedFile.delete();
在此之前的其余代碼是使用Util來復制流,並且它們都工作正常,所以我只需要一個更好的驗證方法。
您可以檢查的一個很棒的方法是比較md5哈希值。 檢查文件長度並不意味着它們是相同的。 雖然md5哈希並不意味着它們也是相同的,但它比檢查長度更好,盡管更長的過程。
public class Main {
public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
System.out.println("Are identical: " + isIdentical("c:\\myfile.txt", "c:\\myfile2.txt"));
}
public static boolean isIdentical(String leftFile, String rightFile) throws IOException, NoSuchAlgorithmException {
return md5(leftFile).equals(md5(rightFile));
}
private static String md5(String file) throws IOException, NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("MD5");
File f = new File(file);
InputStream is = new FileInputStream(f);
byte[] buffer = new byte[8192];
int read = 0;
try {
while ((read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
byte[] md5sum = digest.digest();
BigInteger bigInt = new BigInteger(1, md5sum);
String output = bigInt.toString(16);
return output;
} finally {
is.close();
}
}
}
你可以使用commons io:
org.apache.commons.io.FileUtils.contentEquals(File file1, File file2)
或者您可以使用校驗和方法:
org.apache.commons.io.FileUtils:
static Checksum checksum(File file, Checksum checksum) //Computes the checksum of a file using the specified checksum object.
static long checksumCRC32(File file) //Computes the checksum of a file using the CRC32 checksum routine.
如果在復制流時沒有異常,那么你應該沒問題。 確保不要忽略close方法拋出的異常!
更新:如果您使用FileOutputStream
,您還可以通過在關閉fileOutputStream
之前調用fileOutputStream.getFD().sync()
來確保所有內容fileOutputStream.getFD().sync()
正確寫入。
當然,如果你想絕對確保文件是相同的,你可以比較他們的校驗和/摘要,但這對我來說聽起來有點偏執。
您可以在復制操作中包含校驗和。 對目標文件執行校驗和,並查看它與源上的校驗和匹配。
如果大小不同,也許您在關閉之前不會刷新輸出流。
哪個文件更大? 每個文件的大小是多少? 你真的看過這兩個文件看看有什么不同嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.