我有一个包含图像文件的文件夹。我需要检查是否对此文件夹的内容进行了任何更改。目前,我只是检查是否该文件夹中的文件名称已更改。如何在java中检查图像文件夹的内容是否已更改
我知道,这不是一个好办法做到这一点。有人可以通过替换其中一个图像并将其重命名为替换文件来作弊......但我无法完全弄清楚如何去做它..我应该每个文件并检查其修改时间或一些这样的?
有人可以提出/说明一个替代?
感谢
吉姆
public boolean folderContentsChanged(String folderName,String serializedCacheFileName){
OldFileContents oldContents = readOldContents(serializedCacheFileName);
List<String> oldFileNames = oldContents.getListOfFileNames();
List<String> newFileNames = createFileNamesListFromFolder(folderName);
if(newFileNames.equals(oldFileNames)){
return false;
}else{
return true;
}
}
private OldFileContents readOldContents(String oldCacheFileName){
FileInputStream fin = new FileInputStream(oldCacheFileName);
ObjectInputStream oin = new ObjectInputStream(fin);
OldFileContents oldContents =(OldFileContents) oin.readObject();
return oldContents;
}
更新: 按trashgod的建议,试图比较哈希..代码如下,大约需要55毫秒时间用于比较两个图像..
public class FileHashCompare {
public static byte[] createByteArrayFromFile(File f) throws IOException{
FileInputStream fis = new FileInputStream(f);
long length = f.length();
if (length>Integer.MAX_VALUE){
throw new IllegalArgumentException("file too large to read");
}
byte[] buffer = new byte[(int)length];
int offset = 0;
int bytesRead = 0;
while((offset<buffer.length) && ((bytesRead=fis.read(buffer,offset, buffer.length-offset)) >=0) ){
offset += bytesRead;
}
if (offset < buffer.length) {
throw new IOException("Could not completely read file "+f.getName());
}
fis.close();
return buffer;
}
public static String makeHashOfFile(File f) throws NoSuchAlgorithmException, IOException{
String hashStr = null;
byte[] bytes = createByteArrayFromFile(f);
MessageDigest md = MessageDigest.getInstance("SHA1");
md.reset();
md.update(bytes);
byte[] hash = md.digest();
hashStr = new String(hash);
return hashStr;
}
public static boolean sameFile(File f1,File f2) throws NoSuchAlgorithmException, IOException{
String hash1 = makeHashOfFile(f1);
String hash2 = makeHashOfFile(f2);
if (hash1.equals(hash2)){
return true;
}else{
return false;
}
}
public static void main(String[] args) {
long t1 = System.currentTimeMillis();
try{
File f1 = new File("/home/me/Pictures/painting-bob-ross-landscape-painting-1-21.jpg");
//File f2 = new File("/home/me/Pictures/painting-bob-ross-landscape-painting-1-21 (copy).jpg");
File f3 = new File("/home/me/Pictures/chainsaw1.jpeg");
System.out.println("same file="+sameFile(f1,f3));
long t2 = System.currentTimeMillis();
System.out.println("time taken="+(t2-t1)+" millis");
}catch(Exception e){
e.printStackTrace();
}
}
}
另请参阅如何[在Java中生成MD5哈希](http://stackoverflow.com/questions/415953/generate-md5-hash-in-java)。 – trashgod
从来没有想过这..still,哈希文件可能需要太多的时间,因为整个图像必须阅读..将看到它是如何工作的我的图像收集...(对不起,迟了答复。远离机器) – jimgardener
感谢文档,它的工作速度比我想它会更快 – jimgardener