我正在努力将一些文件移动到项目中的不同目录,它运行良好,但我无法验证它是否已正确移动。
我想验证副本的长度与原始文件的长度相同,然后我想删除原始文件。我在进行验证之前关闭了两个 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();
}
}
}
关于java - 验证文件是否已在 Java 中复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4628769/