Java如何比较两个任意文件是否相同
作者:JFS_Study
这篇文章主要为大家详细介绍了Java如何实现比较两个任意文件是否相同,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下
一、比较规则
- 先比较两个文件的长度,如果不一样则文件肯定不一样。
- 否则将文件读取出来,一个字节一个字节的比较二者内容是否相同。
public class FileCompare {
public static void main(String[] args) {
System.out.println("请依次输入两个文件的全路径和文件名:");
System.out.println("firstFile:");
String firstFile = inputFileName();
System.out.println("secondFile:");
String secondFile = inputFileName();
System.out.println("Start to compare ...");
FileCompare fileCompare = new FileCompare();
fileCompare.compareFile(firstFile, secondFile);
}
private static String inputFileName() {
BufferedReader buffRead = new BufferedReader(new InputStreamReader(System.in));
String fileName = null;
try {
fileName = buffRead.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return fileName;
}
private void compareFile(String firFile, String secFile) {
try {
BufferedInputStream fir = new BufferedInputStream(new FileInputStream(firFile));
BufferedInputStream sec = new BufferedInputStream(new FileInputStream(secFile));
//比较文件的长度是否一样
if (fir.available() == sec.available()) {
while (true) {
int firRead = fir.read();
int secRead = sec.read();
if (firRead == -1 || secRead == -1) {
System.out.println("two files are same!");
break;
} else if (firRead != secRead) {
System.out.println("Files not same!");
break;
}
}
} else {
System.out.println("two files are different!");
}
fir.close();
sec.close();
return;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
二、File 中的 length() 与IO中 InputStream 类中的 available()
1️⃣File 中的 length() 返回 long,表示文件的大小。
2️⃣IO 中 InputStream 类中的 available() 返回 int。表示该 inputstream 在不被阻塞的情况下一次可以读取到的数据长度。
三、方法补充
除了上文的方法,小编还为大家整理了其他Java比较文件的方法,希望对大家有所帮助
java实现两个文件对比
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class check {
public static void main(String[] args) {
Set<String> allStuNames = new HashSet<>();
try {
FileReader fileReader = new FileReader("name.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
// 逐行处理文本内容
// System.out.println(line);
allStuNames.add(line);
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println(allStuNames);
List<String> lst = new ArrayList<>();
try {
FileReader fileReader = new FileReader("a.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
// 逐行处理文本内容
// System.out.println(line);
lst.add(line);
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
for(String desc : lst){
for(String name : allStuNames){
if(desc.contains(name)){
System.out.println(name);
System.out.println(desc);
}
}
}
}
}利用md5判断两个文件是否相同
例子:
根据不同路径下两个文件来判断:
package com.letv.test;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
public class CheckSameFile {
public static char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
public static void main(String[] args) {
String path1 = "d:/test/abc.jpg";
String path2 = "d:/test/asd/abc.jpg";
String hash_path1 = null;
String hash_path2 = null;
try {
hash_path1 = getHash(path1, "MD5");
hash_path2 = getHash(path2, "MD5");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("path1 md5:" + hash_path1);
System.out.println("path2 md5:" + hash_path2);
if (hash_path1.endsWith(hash_path2)) {
System.out.println("文件相同");
} else {
System.out.println("文件不相同");
}
}
/**
* 获得文件md5值
*/
public static String getHash(String fileName, String hashType)
throws Exception {
InputStream fis;
fis = new FileInputStream(fileName);
byte[] buffer = new byte[1024];
MessageDigest md5 = MessageDigest.getInstance(hashType);
int numRead = 0;
while ((numRead = fis.read(buffer)) > 0) {
md5.update(buffer, 0, numRead);
}
fis.close();
return toHexString(md5.digest());
}
/**
* md5转成字符串
*/
public static String toHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++) {
sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
sb.append(hexChar[b[i] & 0x0f]);
}
return sb.toString();
}
}通过比较文件每一个字节判断
public static boolean isSameFile(String filePath1, String filePath2) {
FileInputStream fis1 = null;
FileInputStream fis2 = null;
try {
fis1 = new FileInputStream(filePath1);
fis2 = new FileInputStream(filePath2);
// 获取文件的总字节数
int len1 = fis1.available();
int len2 = fis2.available();
// 判断两个文件的字节长度是否一样,长度相同则比较具体内容
if (len1 == len2) {
// 建立字节缓冲区
byte[] data1 = new byte[len1];
byte[] data2 = new byte[len2];
// 将文件写入缓冲区
fis1.read(data1);
fis2.read(data2);
// 依次比较文件中的每个字节
for (int i = 0; i < len1; i++) {
if (data1[i] != data2[i]) {
System.out.println("文件内容不一样");
return false;
}
}
System.out.println("文件内容相同");
return true;
} else {
// 文件长度不一样,内容肯定不同
System.out.println("文件内容不同");
return false;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
// 关闭资源
if (fis1!=null){
try {
fis1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis2!=null){
try {
fis2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
使用缓冲流比较,在比较大文件时效率相比普通流效率高
public static boolean isSameFile2(String filePath1, String filePath2) {
BufferedInputStream bis1 = null;
BufferedInputStream bis2 = null;
FileInputStream fis1 = null;
FileInputStream fis2 = null;
try {
// 获取文件输入流
fis1 = new FileInputStream(filePath1);
fis2 = new FileInputStream(filePath2);
// 将文件输入流包装成缓冲流
bis1 = new BufferedInputStream(fis1);
bis2 = new BufferedInputStream(fis2);
// 获取文件字节总数
int len1 = bis1.available();
int len2 = bis2.available();
// 判断两个文件的字节长度是否一样,长度相同则比较具体内容
if (len1 == len2) {
// 建立字节缓冲区
byte[] data1 = new byte[len1];
byte[] data2 = new byte[len2];
// 将文件写入缓冲区
bis1.read(data1);
bis2.read(data2);
// 依次比较文件中的每个字节
for (int i = 0; i < len1; i++) {
if (data1[i] != data2[i]) {
System.out.println("文件内容不一致");
return false;
}
}
System.out.println("文件内容一致");
return true;
} else {
System.out.println("文件长度不一致,内容不一致");
return false;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis1 != null) {
try {
bis1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bis2 != null) {
try {
bis2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis1 != null) {
try {
fis1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis2 != null) {
try {
fis2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
将文件分多次读入,然后通过MessageDigest进行MD5加密,最后再通过BigInteger类提供的方法进行16进制的转换
/**
* 计算文件的MD5值
*
* @param file
* @return
*/
public static String getFileMD5(File file) {
if (!file.isFile()) {
return null;
}
MessageDigest digest = null;
FileInputStream in = null;
byte[] buffer = new byte[8192];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer)) != -1) {
digest.update(buffer, 0, len);
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
String filePath1="/Users/zhouzhxu/desktop/test.csv";
String filePath2="/Users/zhouzhxu/desktop/test2.csv";
String fileMD51 = getFileMD5(new File(filePath1));
String fileMD52 = getFileMD5(new File(filePath2));
System.out.println(fileMD51);
System.out.println(fileMD52);
}到此这篇关于Java如何比较两个任意文件是否相同的文章就介绍到这了,更多相关Java比较文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
