tags:

views:

62

answers:

2
public static void main(String argv[]){
    try
         {
        String date=new java.text.SimpleDateFormat("MM-dd-yyyy").format(new java.util.Date());
         File inFolder=new File("Output/" + date + "_4D");
         File outFolder=new File("Output/" + date + "_4D" + ".zip");
      ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFolder)));
      BufferedInputStream in = null;
      byte[] data    = new byte[1000];
      String files[] = inFolder.list();
      for (int i=0; i<files.length; i++)
          {
              in = new BufferedInputStream(new FileInputStream(inFolder.getPath() + "/" + files[i]), 1000);                  
        out.putNextEntry(new ZipEntry(files[i])); 
          int count;
          while((count = in.read(data,0,1000)) != -1)
            {
               out.write(data, 0, count);
            }
          out.closeEntry();
          }
          out.flush();
          out.close();
      }
     catch(Exception e)
     {
              e.printStackTrace();
     } 
}

Am trying to zip a folder which contains subfolders. Trying to zip the folder named 10-18-2010_4D.The above programs ends with the following exception. Please advise on how to clear the issue.

java.io.FileNotFoundException: Output\10-18-2010_4D\4D (Access is denied)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at ZipFile.main(ZipFile.java:17)
+2  A: 

I would include the ant task for zipping - it's way easier to work with. The task calss is: org.apache.tools.ant.taskdefs.Zip (use it programatically)

Bozho
Can you give some points about why we must prefer ant task for zipping?
JavaGeek
it's done in 3 lines of code, and it works. Compare to the above.
Bozho
@Bozho I could find many jar files in the recent version of Ant. which one should be used for Zipping folders?
LGAP
Except if you want to implement zip compression in your own application
jassuncao
@LGAP - see my update. @jassuncao - you can use it programatically
Bozho
Dont we need to add any jar files ? Just importing the avove said class is enough?
LGAP
@LGAP that class is part of the ant jar. Add it to your classpath.
Bozho
Thanks Bozho... But `<zip destfile="${dist}/manual.zip" basedir="htdocs/manual" />` I didnt know how to insert this in a java program.
LGAP
@LGAP use the autocomplete feature of your IDE for the Zip task and it is completely straighforward. I used it the other day without any hassle.
Bozho
+2  A: 

You need to check if the file is a directory because you can't pass directories to the zip method.

Take a look at this page which shows how you can recursively zip a given directory.

dogbane
I think @dogbane is correct. I ran your code using a directory containing only files, and it worked as intended. As soon as I added a nested directoyr, I got the FNF (Access is Denied) exception.
gregcase