COmpressing files and folders in Java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • msankardas
    New Member
    • Nov 2007
    • 7

    #1

    COmpressing files and folders in Java

    Hi,

    As a part of my project, i need to compress folders and files into a single zip file as follows.

    for eg:
    I want to compress
    C:\test\
    c:\compression\
    C:\documents\te st.txt

    all of these into a single zip file... I need to maintain the folder structure as well, when i unzip them using WINZIP.

    I am able to compress each of them seperately, but not together...I am making use of java.util.zip.* ;

    Is there anyway to append more files to an existing zip file??? i am a bit confused with the input and output streams now!!!

    Urgent help required.

    Thanks in advance..

    My code is as follows: [I am open to all suggestions!!!]

    [code=java]
    import java.io.*;
    import java.util.zip.* ;

    public class ZipCreateExampl e {
    static ZipOutputStream cpZipOutputStre am = null;
    String[] strSource=new String[3];
    static String strTarget = "";
    String strSubstring = "";


    public static void main(String[] args) throws IOException
    {
    System.out.prin tln("Example of ZIP file creation.");

    // Specify files to be zipped
    String[] filesToZip = new String[3];
    filesToZip[0] = "C:\\compress.j ava";
    filesToZip[1] = "C:\\test.t xt";
    filesToZip[2] = "C:\\Compresste st";

    int n=filesToZip.le ngth;

    // Specify zip file name
    String zipFileName = "c:\\example2.z ip";

    ZipCreateExampl e udZipUtility = new ZipCreateExampl e();

    for(int i=0;i<n;i++)

    udZipUtility.st rSource[i] = filesToZip[i];
    udZipUtility.st rTarget = zipFileName;

    udZipUtility.zi p(filesToZip,n) ;


    cpZipOutputStre am.close();
    System.out.prin tln("\n Finished creating zip file " + strTarget + " from source ");
    }

    private void zip(String[] filesToZip, int n){
    try
    { ///int count=0;
    for(int i=0;i<n;i++)
    {
    File cpFile = new File(filesToZip[i]);
    System.out.prin tln(filesToZip[i]);
    if (!cpFile.isFile () && !cpFile.isDirec tory() ) {
    System.out.prin tln("\nSource file/directory Not Found!");
    return;
    }
    if (cpFile.isDirec tory()) {
    strSubstring = strSource[i];
    } else {
    strSubstring = "";
    }
    String zipFileName = "c:\\example2.z ip";
    //count=count+1;
    cpZipOutputStre am = new ZipOutputStream (new FileOutputStrea m(zipFileName)) ;
    cpZipOutputStre am.setLevel(9);
    zipFiles(cpFile );

    //cpZipOutputStre am.finish();
    //cpZipOutputStre am.close();
    //System.out.prin tln("\n Finished creating zip file " + strTarget + " from source " + strSource);
    }
    //cpZipOutputStre am.finish();
    cpZipOutputStre am.close();
    //System.out.prin tln("\n Finished creating zip file " + strTarget + " from source ");
    }
    catch (Exception e){
    e.printStackTra ce();
    }

    }

    private void zipFiles(File cpFile) {

    if (cpFile.isDirec tory()) {
    File [] fList = cpFile.listFile s() ;
    for (int i=0; i< fList.length; i++){
    zipFiles(fList[i]) ;
    }
    } else {
    try {
    String strAbsPath = cpFile.getAbsol utePath();
    String strZipEntryName ="";
    if (!strSubstring. equals("") ){
    strZipEntryName = strAbsPath.subs tring(strSource .length+1, strAbsPath.leng th());
    } else {
    strZipEntryName = cpFile.getName( );
    }

    byte[] b = new byte[ (int)(cpFile.le ngth()) ];
    FileInputStream cpFileInputStre am = new FileInputStream (cpFile) ;

    ZipEntry cpZipEntry = new ZipEntry(strZip EntryName);

    // Add ZIP entry to output stream.
    cpZipOutputStre am.putNextEntry (cpZipEntry );
    //int i = cpFileInputStre am.read(b, 0, (int) cpFile.length() );

    cpZipOutputStre am.write(buffer ,0,cpFileInputS tream.read(buff er));
    /*
    int len;
    while ((len = cpFileInputStre am.read(b)) > 0)
    {
    cpZipOutputStre am.write(b,0,le n);
    }
    cpZipOutputStre am.closeEntry() ;

    //cpZipOutputStre am.putNextEntry (cpZipEntry );

    //cpZipOutputStre am.write(b, 0, (int)cpFile.len gth());

    //cpFileInputStre am.close();


    */
    } catch (Exception e) {
    e.printStackTra ce();
    }
    }

    }
    }[/code]
    Last edited by JosAH; Nov 12 '07, 03:33 PM. Reason: added [code] ... [/code] tags
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    That for loop 'for (int i= 0; i < n; i++)' in your main method really looks suspicious.
    You really should fix your indentation and you really should split things up in small
    coherent methods. The little Zip framework is really easy: open a ZipOutputStream ,
    add ZipEntries and their content and close the entire thing again. Next you open
    a ZipFile, read the entries that are in it and read them.

    kind regards,

    Jos

    Comment

    • msankardas
      New Member
      • Nov 2007
      • 7

      #3
      Originally posted by JosAH
      That for loop 'for (int i= 0; i < n; i++)' in your main method really looks suspicious.
      You really should fix your indentation and you really should split things up in small
      coherent methods. The little Zip framework is really easy: open a ZipOutputStream ,
      add ZipEntries and their content and close the entire thing again. Next you open
      a ZipFile, read the entries that are in it and read them.

      kind regards,

      Jos
      sorry abt the indentation... i think the logic which i used is wrong here.
      regarding the zip, i am able to zip a particular file or folder, but the problem arises for the selective zip part.. only the final one gets zipped in the output. the other 2 entries are overwritten by the final entry.

      is it possible to get all the files and folders in a buffer, keep the stream open as each and every file and directory is inserted into the buffer and then zip the whole thing in one go???

      Comment

      • msankardas
        New Member
        • Nov 2007
        • 7

        #4
        Originally posted by msankardas
        sorry abt the indentation... i think the logic which i used is wrong here.
        regarding the zip, i am able to zip a particular file or folder, but the problem arises for the selective zip part.. only the final one gets zipped in the output. the other 2 entries are overwritten by the final entry.

        is it possible to get all the files and folders in a buffer, keep the stream open as each and every file and directory is inserted into the buffer and then zip the whole thing in one go???
        I am able to compress properly now.. was having a small error in the streaming and in the calling of the files. Like u said, my for loop was creating some problems... fixed it now..
        THanks A LOT!!!

        Comment

        Working...