compress folder

hello

i wrote this code to compress directory with subdirectories but it through this exception if the directory contains more than one directory but it works fine with any number of subdirectories for example (C:\Test\New Folder\Copy of New Folder\New Folder\New Folder\New Folder\New Folder\test.java)

publicvoid compressDirectory(boolean firstTime, String directoryPath){

try{

if (firstTime){

String zipfile = directoryPath +".zip";

out =new ZipOutputStream(new FileOutputStream(zipfile));

}

File dir =new File(directoryPath);

String[] entries = dir.list();

byte[] buffer =newbyte[4096];

int bytes_read;

for (int i = 0; i < entries.length; i++){

File f =new File(dir, entries[i]);

if (f.isDirectory())

compressDirectory(false, f.getAbsolutePath());

else{

in =new FileInputStream(f);

ZipEntry entry =new ZipEntry(f.getPath());

out.putNextEntry(entry);

while ((bytes_read = in.read(buffer)) != -1)

out.write(buffer, 0, bytes_read);

}

}

in.close();

out.close();

}catch (Exception c){

c.printStackTrace();

}

}

Exception :

--

java.io.IOException: Stream closed

at java.util.zip.ZipOutputStream.ensureOpen(Unknown Source)

at java.util.zip.ZipOutputStream.putNextEntry(Unknown Source)

at Compress.compressDirectory(Compress.java:46)

at Compress.compressDirectory(Compress.java:42)

at Test.main(Test.java:6)

also i have another problem : Empty folders are ignored

thanks

[2656 byte] By [MohamedSaeeda] at [2007-11-26 18:13:30]
# 1

1. Your recursive method is trying to create the zip file. Why not write a top-level method that creates the zip file, calls a recursive method that does most of the work, then finally closes the file.

2. As for empty directories, why not create zip entries for directories? Right now you are creating entries only for non-directories.

DrLaszloJamfa at 2007-7-9 5:46:35 > top of Java-index,Java Essentials,Java Programming...
# 2
You need to open and close the output file in an outer method that is not called recursively.That would also simplify your logic because you would no longer need the "firstTime" boolean.
TimRyanNZa at 2007-7-9 5:46:35 > top of Java-index,Java Essentials,Java Programming...
# 3

thanks for answering

i did as you said and it works fine but still empty folders don't work fine

i added these lines of code in my function:

if (dir.isDirectory()) {

String[] entries = dir.list();

if(entries.length == 0)

{

ZipEntry entry = new ZipEntry(dir.getPath());

out.putNextEntry(entry);

}

it works fine but the problem is the empty folder is was changed to file with size '0'

thanks

MohamedSaeeda at 2007-7-9 5:46:35 > top of Java-index,Java Essentials,Java Programming...
# 4

yes, i got it

this is the right solution:

if (dir.isDirectory()) {

String[] entries = dir.list();

if(entries.length == 0)

{

ZipEntry entry = new ZipEntry(dir.getPath()+"/");

out.putNextEntry(entry);

}

;)

MohamedSaeeda at 2007-7-9 5:46:36 > top of Java-index,Java Essentials,Java Programming...