我有一个包含图像文件的文件夹。我需要检查是否对该文件夹的内容进行了任何更改。目前,我只是检查该文件夹中的文件名是否已更改。
我知道,这不是一个好方法。有人可以通过替换其中一张图像并将其重命名为替换文件来作弊..但我不太清楚该怎么做..我应该把每个文件并检查其修改时间或类似时间?
有人可以建议/说明替代方案吗?
谢谢
吉姆
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();
}
}
}
最佳答案
看看是什么Commons IO具有:FileAlterationMonitor
可能会执行您想要的操作。
关于java - 如果 imagefolder 的内容已更改,如何检查 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6970917/