Search ZipEntry using breadth-first search approach in java

Viewed 69

I'm having issues finding a way to iterate through ZipFile in java in breadth-first search way.

I've found that getting all entries using either ZipInputStream either enumeration method sorts them in depth-first search way. I've also checked with using debug.

Code 1:

ZipInputStream zf = new ZipInputStream(inputStream);
ZipEntry[] entries;
ZipEntry zipEntry;

while ((zipEntry = zf.getNextEntry()) != null)
{
  entries.add(zipEntry);
}

Code 2:

ZipEntry[] entries;
Enumeration<ZipEntry> enumeration = zipFile.entries();

while (enumeration.hasMoreElements())
{
  entries.add(en.nextElement());
}

Example zip file:

foo.zip
| -- folder1
|    | -- file11
|    | -- file12
| -- folder2
|    | -- file21
|    | -- file22
| -- lorem.txt

I would like to get entries in following order:

1. folder1/
2. folder2/
3. lorem.txt
4. folder1/file11
5. folder1/file12
6. folder2/file21
7. folder2/file22

and so on...

But instead I'm getting it like:

1. folder1/
2. folder1/file11
3. folder1/file12
4. folder2/
5. folder2/file21
6. folder2/file22
7. lorem.txt

Does anyone have an idea how can I achieve my goal?

2 Answers

The standard library does not offer this functionality you'll have to do it yourself.

Put the entries in a new list and sort it by depth then by name:

List<ZipEntry> entries = new ArrayList<>();
Enumeration<? extends ZipEntry> entriesEnum = zipFile.entries();
while(entriesEnum.hasMoreElements()) entries.add(entriesEnum.nextElement());
entries.sort(Comparator.<ZipEntry, Integer>comparing(e -> e.getName().split("/").length).thenComparing(ZipEntry::getName));

You can now iterate over that list to traverse the entries in breadth-first order.

This is somewhat of a hack because we are not really traversing a tree, but it yields the same result.

其实ZipEntry只是作为一个定位,所以你不能单独的试图用ZipEntry的顺序来获取到真正的流,你这个问题其实意义不大

In my opinion ,The ZipEntry is just a location, so you can't just try to get a real stream using the order of the ZipEntry, so your question doesn't really matter

Related