有什么方法可以在 Android 中比较两个文件?
For example: I am having two files under same folder, which are same. They are same(also in size), but their namea are like
myFileA.pdf
andmyFileB.pdf
. So how can I identify that they are same or not.
我已经尝试过的:
compareTo()
方法:尝试了myFileA.compare(myFileB)
,但这给出了一些奇怪的值,例如 -1、-2、等。我认为这些值是文件的 PATH 相关的。myFile.length()
:但在一些极少数情况下(非常罕见的情况下),两个不同的文件可以具有相同的大小,所以我认为这不是正确的方法。
NOTE: I told that files are under same folder for just example, they can be anywhere like
myFileA.pdf
can be inNewFolder1
andmyFileB.pdf
can be inNewFolder2
.
最佳答案
前段时间我编写了一个实用程序来以高效的方式比较两个流的内容:当发现第一个差异时停止比较。 这是我认为很容易 self 解释的代码:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
public class FileComparator implements Comparator<File> {
@Override
public int compare(File file1, File file2) {
// one or both null
if (file1 == file2) {
return 0;
} else if (file1 == null && file2 != null) {
return -1;
} else if (file1 != null && file2 == null) {
return 1;
}
if (file1.isDirectory() || file2.isDirectory()) {
throw new IllegalArgumentException("Unable to compare directory content");
}
// not same size
if (file1.length() < file2.length()) {
return -1;
} else if (file1.length() > file2.length()) {
return 1;
}
try {
return compareContent(file1, file2);
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
private int bufferSize(long fileLength) {
int multiple = (int) (fileLength / 1024);
if (multiple <= 1) {
return 1024;
} else if (multiple <= 8) {
return 1024 * 2;
} else if (multiple <= 16) {
return 1024 * 4;
} else if (multiple <= 32) {
return 1024 * 8;
} else if (multiple <= 64) {
return 1024 * 16;
} else {
return 1024 * 64;
}
}
private int compareContent(File file1, File file2) throws IOException {
final int BUFFER_SIZE = bufferSize(file1.length());
// check content
try (BufferedInputStream is1 = new BufferedInputStream(new FileInputStream(file1), BUFFER_SIZE); BufferedInputStream is2 = new BufferedInputStream(new FileInputStream(file2), BUFFER_SIZE);) {
byte[] b1 = new byte[BUFFER_SIZE];
byte[] b2 = new byte[BUFFER_SIZE];
int read1 = -1;
int read2 = -1;
int read = -1;
do {
read1 = is1.read(b1);
read2 = is2.read(b2);
if (read1 < read2) {
return -1;
} else if (read1 > read2) {
return 1;
} else {
// read1 is equals to read2
read = read1;
}
if (read >= 0) {
if (read != BUFFER_SIZE) {
// clear the buffer not filled from the read
Arrays.fill(b1, read, BUFFER_SIZE, (byte) 0);
Arrays.fill(b2, read, BUFFER_SIZE, (byte) 0);
}
// compare the content of the two buffers
if (!Arrays.equals(b1, b2)) {
return new String(b1).compareTo(new String(b2));
}
}
} while (read >= 0);
// no difference found
return 0;
}
}
}
关于java - 如何以编程方式比较两个 java.io.File,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38527245/