I want to pack a directory of other directories into a zip file. These other directories contain a text file and a PNG file each. However, FileUtils.listFilesAndDirs() lists these directories AND their children, and upon packing them into a zip, it packs the directories and their children, but also it packs a copy of the children into the root of the zip.
The zip looks like this:
Class1
-Image1
-Text1
Class2
-Image2
-Text2
Class3
-Image3
-Text3
Image1
Text1
Image2
Text2
Image3
Text3
It should not have the files after the empty line. Are there any alternative functions that could list just the directories and their children, and not list the children separately?
Sounds to me like some misunderstanding when working with file/directory filters and ZipOutputStream
. How about something like this?
import java.io.*;
import java.util.Collection;
import java.util.zip.*;
import javax.swing.JPanel;
import org.apache.commons.io.*;
import org.apache.commons.io.filefilter.*;
public class Demo extends JPanel {
private static final long serialVersionUID = 1L;
public static void main(String s[]) throws Exception {
Demo demo = new Demo();
demo.launch();
}
private void launch() throws Exception {
Collection<File> fs = FileUtils.listFilesAndDirs(new File("/tmp/fakerepo"),
FileFileFilter.FILE, DirectoryFileFilter.DIRECTORY);
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new FileOutputStream("/tmp/test.zip"));
for (File f : fs) {
System.out.println(f.getAbsolutePath());
if (!f.isFile())
continue;
ZipEntry ze = new ZipEntry(f.getAbsolutePath());
zos.putNextEntry(ze);
InputStream is = null;
try {
is = new FileInputStream(f);
IOUtils.copy(is, zos);
} finally {
IOUtils.closeQuietly(is);
}
}
zos.flush();
} finally {
IOUtils.closeQuietly(zos);
}
}
}