gpt4 book ai didi

android - 加快文件数组的 MD5 检查

转载 作者:行者123 更新时间:2023-11-29 01:47:08 24 4
gpt4 key购买 nike

我正在遍历一个文件数组以查看其中是否有任何文件与该数组中的最后一个文件匹配:

    List<File> files = Arrays.asList(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).listFiles());
byte[] md5Downloaded = null;
try {
md5Downloaded = createChecksum(files.get(files.size()-1).getAbsolutePath());
} catch (Exception e1) {
e1.printStackTrace();
}

for(File file : files){

try {
byte[] md5CurrentFile = createChecksum(file.getAbsolutePath());


if(Arrays.equals(md5Downloaded, md5CurrentFile) && counter != files.size()-1 ){
alertUserMD5(file, files.get(files.size()-1));
return;
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

这里是createChecksum方法,是借用的:

private static byte[] createChecksum(String filename) throws Exception {
InputStream fis = new FileInputStream(filename);

byte[] buffer = new byte[1024];
MessageDigest complete = MessageDigest.getInstance("MD5");
int numRead;

do {
numRead = fis.read(buffer);
if (numRead > 0) {
complete.update(buffer, 0, numRead);
}
} while (numRead != -1);

fis.close();
return complete.digest();
}

但是,我对这个过程花费的时间(大约 15 秒)不满意。我意识到我正在做的事情在很大程度上取决于列表中的文件数量以及这些文件的大小,但是有什么方法可以加快速度吗?

最佳答案

private void searchFile() {
long t = System.currentTimeMillis();
List<File> files = new ArrayList<File>(Arrays.asList(dir.listFiles()));
File downloaded = files.get(files.size() - 1);
files.remove(files.size()-1);
byte[] md5Downloaded = null;
try {
md5Downloaded = createChecksum(downloaded.getAbsolutePath());
} catch (Exception e1) {
e1.printStackTrace();
}

Collections.sort(files, new Comparator<File>() {
@Override
public int compare(File lhs, File rhs) {
return Long.valueOf(lhs.length()).compareTo(rhs.length());
}
});

final byte[] MD5 = md5Downloaded;

final int position = Collections.binarySearch(files, downloaded, new Comparator<File>() {
@Override
public int compare(File lhs, File rhs) {
int compare = Long.valueOf(lhs.length()).compareTo(rhs.length());
if (compare == 0) {
try {
if (Arrays.equals(MD5, createChecksum(lhs.getAbsolutePath()))) {
return 0;
}
} catch (Exception ignored) {

}
return -1;
} else
return compare;
}
});

if (position >= 0) {
alertUserMD5(files.get(position), downloaded);
}

}

对于损坏的示例,我们深表歉意,它是“在纸上”完成的。这是工作示例。已在包含 578 个文件的目录中对其进行测试 = 154 毫秒

关于android - 加快文件数组的 MD5 检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20775056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com