Reputation: 1078
I am deleting diretory after zipped the same. I used the following code to make zip and delete.
I am able to do zip and cant delete the folder.
Can anyone point me where I am doing mistake.
Here the code I m using
public class ZipDirectory {
public static void main(String[] a) throws Exception {
zipFolder("d:\\conf2", "d:\\conf2.zip");
}
static public void zipFolder(String srcFolder, String destZipFile) throws Exception {
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
addFolderToZip("", srcFolder, zip);
zip.flush();
zip.close();
delete(new File(srcFolder));
}
static private void addFileToZip(String path, String srcFile, ZipOutputStream zip)
throws Exception {
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);
}
}
}
static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip)
throws Exception {
File folder = new File(srcFolder);
for (String fileName : folder.list()) {
addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip);
}
}
static private void delete (File path){
if( path.exists() ) {
File[] files = path.listFiles();
for(int i=0; i<files.length; i++) {
files[i].delete();
}
}
path.delete();
}
}
Upvotes: 1
Views: 679
Reputation: 1132
On taking trace of the delete method it shows the below
07:58:12.734018754 0x2970500 mt.0 Entry >java/io/File.delete()Z Bytecode method, This = 0xfffc4810
07:58:12.734019108 0x2970500 mt.3 Entry >java/lang/System.getSecurityManager()Ljava/lang/SecurityManager; Bytecode static method
07:58:12.734019462 0x2970500 mt.9 Exit
07:58:12.734019815 0x2970500 mt.0 Entry >java/io/File.isInvalid()Z Bytecode method, This = 0xfffc4810
On deleting the file, security manager refuse to delete the file because of already existing file descriptor associated to that. Close the Fileinput stream to avoid this condition.
Upvotes: 1
Reputation: 8388
Please close FileInputStream
's instance to make your deletion successful.
please add in.close()
in addFileToZip()
method.
Upvotes: 4
Reputation: 3600
You are not colling the ZipOutputStream object that you have created. Try replacing following method in you code. Here I have created ZipOutputStrean object in try-with-resource and it worked
static public void zipFolder(String srcFolder, String destZipFile) throws Exception {
try(ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(destZipFile)))
{
addFolderToZip("", srcFolder, zip);
zip.flush();
zip.close();
delete(new File(srcFolder));
}
}
Upvotes: 0