判断两个文件是否存储相同的内容 [英] Determine if two files store the same content

查看:30
本文介绍了判断两个文件是否存储相同的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何编写一个 java 函数 boolean sameContent(Path file1,Path file2) 来确定两个给定的路径是否指向存储相同内容的文件?当然,首先,我会检查文件大小是否相同.这是存储相同内容的必要条件.但是我想听听你的方法.如果这两个文件存储在同一个硬盘驱动器上(就像在我的大多数情况下一样),这可能不是在两个流之间跳转太多次的最佳方式.

How would you write a java function boolean sameContent(Path file1,Path file2)which determines if the two given paths point to files which store the same content? Of course, first, I would check if the file sizes are the same. This is a necessary condition for storing the same content. But then I'd like to listen to your approaches. If the two files are stored on the same hard drive (like in most of my cases) it's probably not the best way to jump too many times between the two streams.

推荐答案

Apache commons IO 的 FileUtils.contentEquals 方法和 api 正是 此处.

Exactly what FileUtils.contentEquals method of Apache commons IO does and api is here.

尝试以下操作:

File file1 = new File("file1.txt");
File file2 = new File("file2.txt");
boolean isTwoEqual = FileUtils.contentEquals(file1, file2);

在实际进行比较之前,它会进行以下检查:

It does the following checks before actually doing the comparison:

  • 两个文件都存在
  • 传递的两个文件都是文件类型而不是目录.
  • 长度(以字节为单位)不应相同.
  • 两者都是不同的文件,并不完全相同.
  • 然后比较内容.

这篇关于判断两个文件是否存储相同的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆