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

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

问题描述

如何编写一个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:


  • 这两个文件都存在

  • 传递的文件都是文件类型而不是目录。

  • 以字节为单位的长度不应该相同。

  • 两者都是不同的文件,不一样。


  • existence of both the files
  • Both file's that are passed are to be of file type and not directory.
  • length in bytes should not be the same.
  • Both are different files and not one and the same.
  • Then compare the contents.

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

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