有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

复制验证文件是否在Java中复制

我正在将一些文件移动到我项目中的另一个目录中,效果很好,只是我无法验证它是否被正确移动

我想验证副本的长度是否与原件相同,然后我想删除原件。我在进行验证之前关闭了两个文件流,但仍然失败,因为大小不同。下面是我关闭流、验证和删除的代码

 in.close();
 out.close();

 if (encCopyFile.exists() && encCopyFile.length() == encryptedFile.length())
     encryptedFile.delete();

在此之前的其余代码都是使用Util来复制流,而且一切正常,所以我真的需要一种更好的验证方法


共 (3) 个答案

  1. # 1 楼答案

    检查的一个好方法是比较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();
            }
        }
    }
    
  2. # 2 楼答案

    如果大小不同,可能在关闭输出流之前没有刷新它

    哪个文件更大?每个文件的大小是多少?你真的看过这两个文件,看看有什么不同吗

  3. # 3 楼答案

    您可以使用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.