我有一個包含圖像文件的文件夾。我需要檢查是否對此文件夾的內容進行了任何更改。目前,我只是檢查是否該文件夾中的文件名稱已更改。如何在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