I am trying to zip the content of the folder. Meaning when I unzip the zip I don't want to get the folder but the content of the folder. Content is various files and subfolder
Problem: However when I do this, the zip that gets created does not show my files it only shows the folders. When I use different unzip utilities I can see that the files are there. It feels like some kind of security setting was applied or maybe they are made hidden. I need to be able to see the files as it is causing problems with my other programs.
The structure should look like this
NOT LIKE THIS
Here is the code I am using
//create flat zip
FileOutputStream fileWriter = new FileOutputStream(myfolder +".zip");
ZipOutputStream zip = new ZipOutputStream(fileWriter);
File folder = new File(myfolder);
for (String fileName: folder.list()) {
FileUtil.addFileToZip("", myfolder + "/" + fileName, zip);
}
zip.flush();
zip.close();
//end create zip
Here is the code in my FileUtil
public static void addFileToZip(String path, String srcFile,ZipOutputStream zip) throws IOException {
File folder = new File(srcFile);
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, zip);
}
else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
zip.closeEntry();
zip.flush();
in.close();
//zip.close();
}
}
public static void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws IOException {
File folder = new File(srcFolder);
//System.out.println("Source folder is "+srcFolder+" into file "+folder);
for (String fileName: folder.list()) {
if (path.equals("")) {
addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
}
else {
//System.out.println("zipping "+path + "/" + folder.getName()+" and file "+srcFolder + "/" + fileName);
addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip);
}
}
}
Thank you for any help in advance, I feel like it is just a minor thing that I might be missing here.
In addFileToZip
method, you have
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
You will get a "/"
appended with folder.getName()
when the path
is blank. This could be your problem?
Try
if (path.equals("")) {
zip.putNextEntry(new ZipEntry(folder.getName()));
}
else {
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
}