Not able to put some files inside Zip file
Hi All,
Can any one please let me know how to zip a directory which contains .xml and .txt files with sub directories?
I tried below code but, its placing all the .xml, .txt files from the directory and sub directory and the sub-directory itself.
for ex: zip1 is a directory {123.xml, 234.xml and zip234 as sub-directory}
Now, i want to zip this files and sub-directories i.e. ZipTest.zip file should contain 123.xml, 234.xml and zip234, zip345 as sub-directory.
And zip234 sub-directory can contain some more sub-directory.
Code Java:
public static void main(String[] args) {
String zipFileName = "C:\\compressed3.zip";
ZipOutputStream zout;
try {
zout = new ZipOutputStream(new FileOutputStream(zipFileName));
createZipFile("C:\\testZip", zout);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void createZipFile(String string, ZipOutputStream zout) {
FileInputStream fis = null;
try {
/*ZipFile zipFile = new ZipFile(string);
ZipEntry entry = zipFile.getEntry(string);*/
File die = new File(string);
File[] files = die.listFiles();
for (int i =0; i<files.length;i++){
if(files[i].isDirectory())
{
//if the File object is a directory, call this
//function again to add its content recursively
//String filePath = f.getPath();
String filePath = files[i].getPath();
createZipFile(filePath, zout);
//loop again
continue;
}
fis = new FileInputStream(files[i]);
zout.putNextEntry(new ZipEntry(files[i].getName()));
byte[] buffer = new byte[1024];
int bytesRead;
//Each chunk of data read from the input stream
//is written to the output stream
while ((bytesRead = fis.read(buffer)) > 0) {
zout.write(buffer, 0, bytesRead);
}
//Close zip entry and file streams
zout.closeEntry();
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
zout.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Please Advice.
Thanks,
Chinnu