0

I am using java.util.zip to zip up some files in java. The problem that I am having is that the zipped file will create folders for all the parent directories. For example, if I have a file at C:/folder1/folder2/folder3/file.txt

This will create a zipped file with a folder named folder 1, then folder 2, and so on until file.txt.

The result that I am looking for is a zipped folder with just the file.txt file at the root without any folders.

Here is some sample code

BufferedInputStream origin = null;
         FileOutputStream dest = new 
           FileOutputStream("c:\\zip\\myfigs.zip");
         ZipOutputStream out = new ZipOutputStream(new 
           BufferedOutputStream(dest));
         //out.setMethod(ZipOutputStream.DEFLATED);
         byte data[] = new byte[BUFFER];
         // get a list of files from current directory
         String files[] = {"C:/folder1/folder2/folder3/file.txt"};

         for (int i=0; i<files.length; i++) {
            System.out.println("Adding: "+files[i]);
            FileInputStream fi = new 
              FileInputStream(files[i]);
            origin = new 
              BufferedInputStream(fi, BUFFER);
            ZipEntry entry = new ZipEntry(files[i]);
            out.putNextEntry(entry);
            int count;
            while((count = origin.read(data, 0, 
              BUFFER)) != -1) {
               out.write(data, 0, count);
            }
            origin.close();
         }
         out.close();
      } catch(Exception e) {
         e.printStackTrace();
      }
boyco
  • 557
  • 1
  • 5
  • 9

1 Answers1

1

Replace this line

ZipEntry entry = new ZipEntry(files[i]);

by

ZipEntry entry = new ZipEntry(files[i].substring(files[i].lastIndexOf("/")+1));

When you create the zipEntry, you need to specify the file name not the full path.

EDIT:

A cleaner way would (like Louis Wasserman commented) would be to use the File object and to get the file name. This will be a way to check if the file exists before zipping it.

VirtualTroll
  • 3,077
  • 1
  • 30
  • 47