Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2005

Tip: Looking for answers? Try searching our database.

Zipping dir and avoiding absolute path

Thread view: 
iksrazal@terra.com.br - 11 Nov 2005 14:54 GMT
Hi all,

I want to zip this directory:

mydir

The abolute path is:

/home/iksrazal/somepath/mydir

When I unzip the file I created, I get:

/home/iksrazal/somepath/mydir

But I just want:

mydir

Here's my code, please help. It runs in a servlet container like
tomcat. Note - the code doesn't use 'shouldDeleteDir' yet. And it uses
recursion. The code is based off of http://www.devx.com/tips/Tip/14049
.

/** Convert directories and files to zip format. */
public class Zipper {

   /** commons logging declaration. **/
   private static Log logger = LogFactory.getLog(
           Zipper.class);

   /** Exceptions via a Inner Class. **/
   static class SWAZipException extends Exception {
       /** Java 5.0 comparison utilty - without it gives warnings. */
       static final long serialVersionUID = -1L;

       /** Customized exception.
        * @param msg - Stacktrace
        * @param cause - Troublemaker
        */
       public SWAZipException(String msg, Throwable cause) {
           super(msg, cause);
       }
   }

   /** Convert directory to a zip file, removing dir if desired.
    * @param dir2zip The directory to zip
    * @param shouldDeleteDir delete if true, otherwise do nothing
    */
   public static void zipDir(String dir2zip, boolean shouldDeleteDir)
{

       try {
           logger.warn("Zipping dir : "
                   + dir2zip);
           ZipOutputStream zos = new ZipOutputStream(
                   new FileOutputStream(dir2zip + ".zip"));
           zipDir(dir2zip, shouldDeleteDir, zos);
           zos.close();
       } catch (Exception ex) {
           logger.error(ex.getMessage(), ex);
       }

   }

   /** Convert directory to a zip file, removing dir if desired.
    *  Pass a ZipOutputStream so we can recursively zip
    *  sub-directories
    * @param dir2zip The directory to zip
    * @param shouldDeleteDir delete if true, otherwise do nothing
    * @param zos Pass in a reference so recursion can be performed
    * @throws SWAZipException pass all errors up to caller
    */
   private static void zipDir(String dir2zip, boolean shouldDeleteDir,
           ZipOutputStream zos) throws SWAZipException {

       try {
           // zip filename == dir name + .zip
           File zipDir = new File(dir2zip);
           //get a listing of the directory content
           String[] dirList = zipDir.list();
           byte[] readBuffer = new byte[2156];
           int bytesIn = 0;
           // loop through dirList, and zip the files
           for (int i = 0; i < dirList.length; i++) {
               File f = new File(zipDir, dirList[i]);
               if (f.isDirectory()) {
                   //if the File object is a directory, call this
                   //function again to add its content recursively
                   String filePath = f.getPath();
                   zipDir(filePath, shouldDeleteDir, zos);
                   //loop again
                   continue;
               }
               // if we reached here, the File object f was not
               // a directory
               // create a FileInputStream on top of f
               FileInputStream fis = new FileInputStream(f);
               // create a new zip entry
               ZipEntry anEntry = new ZipEntry(f.getPath());
               //place the zip entry in the ZipOutputStream object
               zos.putNextEntry(anEntry);
               //now write the content of the file to the
ZipOutputStream
               while ((bytesIn = fis.read(readBuffer)) != -1) {
                   zos.write(readBuffer, 0, bytesIn);
               }
               //close the Stream
               fis.close();
           }
       } catch (Exception ex) {
           throw new SWAZipException(ex.getMessage(), ex);
        }
   }
}
Andrey Kuznetsov - 11 Nov 2005 15:56 GMT
You need something like this:

String pathToDir = "/home/iksrazal/somepath";

<snip>

ZipEntry anEntry = new ZipEntry(f.getPath().substring(pathToDir.length()));

Signature

Andrey Kuznetsov
http://uio.imagero.com Unified I/O for Java
http://reader.imagero.com Java image reader
http://jgui.imagero.com Java GUI components and utilities



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.