I'd like to explain in more details why Vikram's answer is correct and the accepted and highest scoring answers are potentially misleading or incomplete.
As Vikram stated (correctly)
The order you add entries to the ZipOutputStream
is the order they are physically located in the .zip file.
I found this part of the accepted answer to be potentially misleading:
It will also print in the same order as it is displayed inside the zip.
One gotcha I'd like to note is that files within a folder are not guaranteed to be returned in succession.
Different tools display zip file contents in different orders. In particular any tools with a GUI will show all files in a folder together whereas the actual files within the zip they may be scattered throughout.
Let's walk through the two scenarios below.
Scenario 1: Files in Tree Order
Starting with a file tree like this
$ tree
├── folder1
│ ├── bar.java
│ └── foo.c
├── foobar.c
├── hello.c
└── world.java
Now let's create a zip from this directory using the Linux zip
command.
$ zip -r zip1.zip ./*
adding: folder1/ (stored 0%)
adding: folder1/foo.c (stored 0%)
adding: folder1/bar.java (stored 0%)
adding: foobar.c (stored 0%)
adding: hello.c (stored 0%)
adding: world.java (stored 0%)
Note the order these files were added. This is the same order that they will be iterated through when using ZipOutputStream
. Test that with the following script (borrowed from Zoop's answer)
jshell> import java.util.zip.*;
...> ZipInputStream zis = new ZipInputStream(new FileInputStream("./zip1.zip"));
...> ZipEntry temp = null;
...> while ( (temp = zis.getNextEntry()) != null )
...> {
...> System.out.println(temp.getName());
...> }
folder1/
folder1/foo.c
folder1/bar.java
foobar.c
hello.c
world.java
Scenario 2: Files Scattered
If we add the files in a different order then they will be iterated through in a different order. Let's try that by using the zip command to create a new file which we add files to 1-by-1:
zip -m zip1.zip ./hello.c
zip -m zip1.zip ./folder1
zip -m zip2.zip ./folder1/foo.c
zip -m zip1.zip ./world.java
zip -m zip1.zip ./foobar.c
zip -m zip1.zip ./folder1/bar.java # Notice we're adding this LAST
Now if we iterate through the files you'll see that folder1/bar.java
is the last entry because it was added last. It will not be returned alongside the other folder contents. The directory entry will not be duplicated or immediately precede it.
hello.c
folder1/
folder1/foo.c
world.java
foobar.c
folder1/bar.java
The zip spec is quite complex so be very careful when using ZipInputStream.