问题
I'm currently developing a tool that would allow me to modify the md5 of a zip file. The directory structure of the file looks like
baselines->
models -> icons ->
lang ->
(a bunch of files here)
However, when I run my code, none of those directories are getting iterating into. The output gives me:
Name:model/visualization_dependency.xml
Name:model/visualization_template.xml
Name:model/weldmgmt_dependency.xml
Name:model/weldmgmt_template.xml
I was expecting to something like model/baseline/somefile.xml appears on the output, but it does not. Any Thoughts?
byte[] digest = null;
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
ZipEntry current;
while((current = entry.getNextEntry()) != null){
//ZipEntry current = entry.getNextEntry();
System.out.println("Size:" + current.getSize());
System.out.println("Name:" + current.getName());
if(current.isDirectory()){
digest = this.encodeUTF8(current.getName());
md5.update(digest);
}
else{
int size = (int)current.getSize();
digest = new byte[size];
entry.read(digest, 0, size);
md5.update(digest);
}
}
digest = md5.digest();
entry.close();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
回答1:
Once you check that existing folder is directory then you need to iterative go through each files in the directory and process each on of those.
Example:
if(current.isDirectory()){
System.out.println("Directory: " + file.getName());
//Get list of files by file.listFiles() and pass it to
// to other method that will do processing.
digest = this.encodeUTF8(current.getName());
md5.update(digest);
}
Checkout this question, it details process well. Iterating inside directories in Java
回答2:
I think your code is perfect. I suspect your zip file does not contain directories. They don't have to!
For example, here's a zip file I created with "a/b/c/d.txt". When I initially created it the directories were added to the zip file:
$ unzip -l a.zip
Archive: a.zip
Length Date Time Name
--------- ---------- ----- ----
0 2012-06-12 14:22 a/
0 2012-06-12 14:22 a/b/
0 2012-06-12 14:22 a/b/c/
19 2012-06-12 14:22 a/b/c/d.txt
--------- -------
19 4 files
But then I deleted the directories from the zip index:
$ zip -d a.zip a/b/c
deleting: a/b/c/
$ zip -d a.zip a/b
deleting: a/b/
$ zip -d a.zip a
deleting: a/
And now when I listed its contents, sure enough, only the file appears. The directories are gone:
$ unzip -l a.zip
Archive: a.zip
Length Date Time Name
--------- ---------- ----- ----
19 2012-06-12 14:22 a/b/c/d.txt
--------- -------
19 1 file
Note: when I unzipped this same file, it created the a/b/c/ directory before extracting the d.txt file, even though the zip index itself contained no directories. So it looks like directory entries in zip files are completely optional.
来源:https://stackoverflow.com/questions/11004811/iterating-over-all-directories-in-a-zip-file-java