473,402 Members | 2,053 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,402 software developers and data experts.

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\test.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!!!]

Expand|Select|Wrap|Line Numbers
  1. import java.io.*;
  2. import java.util.zip.*;
  3.  
  4. public class ZipCreateExample {
  5.     static ZipOutputStream cpZipOutputStream = null;  
  6.          String[] strSource=new String[3];
  7.          static String strTarget = "";
  8.           String strSubstring = "";
  9.  
  10.  
  11.          public static void main(String[] args) throws IOException 
  12.     {
  13.      System.out.println("Example of ZIP file creation.");
  14.  
  15.      // Specify files to be zipped
  16.      String[] filesToZip = new String[3];
  17.      filesToZip[0] = "C:\\compress.java";
  18.      filesToZip[1] = "C:\\test.txt";
  19.      filesToZip[2] = "C:\\Compresstest";
  20.  
  21.      int n=filesToZip.length;
  22.  
  23.      // Specify zip file name
  24.      String zipFileName = "c:\\example2.zip";
  25.  
  26.      ZipCreateExample udZipUtility = new ZipCreateExample();
  27.  
  28.         for(int i=0;i<n;i++)
  29.  
  30.             udZipUtility.strSource[i] = filesToZip[i];
  31.             udZipUtility.strTarget = zipFileName;
  32.  
  33.             udZipUtility.zip(filesToZip,n);
  34.  
  35.  
  36.            cpZipOutputStream.close();
  37.            System.out.println("\n Finished creating zip file " + strTarget + " from source ");
  38.     }
  39.  
  40.    private void zip(String[] filesToZip, int n){
  41.         try
  42.         {  ///int count=0;
  43.             for(int i=0;i<n;i++)
  44.             {
  45.                File cpFile = new File(filesToZip[i]);
  46.                System.out.println(filesToZip[i]);
  47.                if (!cpFile.isFile() && !cpFile.isDirectory() ) {
  48.                 System.out.println("\nSource file/directory Not Found!");
  49.                 return;
  50.             }
  51.             if  (cpFile.isDirectory()) {
  52.                 strSubstring = strSource[i];
  53.             } else {
  54.                 strSubstring = "";
  55.             }
  56.             String zipFileName = "c:\\example2.zip";
  57.             //count=count+1;
  58.             cpZipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
  59.             cpZipOutputStream.setLevel(9);
  60.             zipFiles(cpFile);
  61.  
  62.             //cpZipOutputStream.finish();
  63.             //cpZipOutputStream.close();
  64.             //System.out.println("\n Finished creating zip file " + strTarget + " from source " + strSource);
  65.         }
  66.         //cpZipOutputStream.finish();
  67.         cpZipOutputStream.close();
  68.         //System.out.println("\n Finished creating zip file " + strTarget + " from source ");
  69.         }
  70.         catch (Exception e){
  71.             e.printStackTrace();
  72.         }
  73.  
  74. }
  75.  
  76. private void  zipFiles(File cpFile) {
  77.  
  78.     if (cpFile.isDirectory()) {
  79.         File [] fList = cpFile.listFiles() ;
  80.         for (int i=0; i< fList.length; i++){
  81.             zipFiles(fList[i]) ;
  82.         }
  83.     } else {
  84.         try {
  85.             String strAbsPath = cpFile.getAbsolutePath();
  86.             String strZipEntryName ="";
  87.             if (!strSubstring.equals("") ){
  88.                 strZipEntryName  = strAbsPath.substring(strSource.length+1, strAbsPath.length());
  89.             } else {
  90.                 strZipEntryName  = cpFile.getName();
  91.             }
  92.  
  93.             byte[] b = new byte[ (int)(cpFile.length()) ];
  94.             FileInputStream cpFileInputStream = new FileInputStream (cpFile) ;
  95.  
  96.             ZipEntry cpZipEntry = new ZipEntry(strZipEntryName);
  97.  
  98. //             Add ZIP entry to output stream.
  99.             cpZipOutputStream.putNextEntry(cpZipEntry );
  100.             //int i = cpFileInputStream.read(b, 0, (int) cpFile.length());
  101.  
  102.             cpZipOutputStream.write(buffer,0,cpFileInputStream.read(buffer));
  103.             /*
  104.             int len;
  105.             while ((len = cpFileInputStream.read(b)) > 0)
  106.             {
  107.                 cpZipOutputStream.write(b,0,len);
  108.            }
  109.             cpZipOutputStream.closeEntry();
  110.  
  111.             //cpZipOutputStream.putNextEntry(cpZipEntry );
  112.  
  113.             //cpZipOutputStream.write(b, 0, (int)cpFile.length());
  114.  
  115.             //cpFileInputStream.close();
  116.  
  117.  
  118.             */
  119.         } catch (Exception e) {
  120.             e.printStackTrace();
  121.         }
  122.     }
  123.  
  124. }
  125. }
Nov 12 '07 #1
3 3208
JosAH
11,448 Expert 8TB
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
Nov 12 '07 #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
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???
Nov 13 '07 #3
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!!!
Nov 13 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Yuancai \(Charlie\) Ye | last post by:
Hi, All: I am happy to annouce that we have formally released our latest SocketPro version 4 at www.udaparts.com, an advanced remoting framework written from batching/queue, asynchrony and...
1
by: G.M. Harland | last post by:
Please keep in mind that I am a PowerBuilder developer working on his first ..NET project. I have a VB.NET console app that is responsible for taking MS Word docs and getting them into an Oracle...
6
by: sri2097 | last post by:
Hi, I'm trying to zip a particular fiolder and place the zipped folder into a target folder using python. I have used the following command in 'ubuntu'. zip_command = 'zip -qr %s %s' % (target,...
4
by: sri2097 | last post by:
Hi all,This is in reply to the 'Compressing folders in Windows using Python' query I raised y'day. I figured out that windows does not allow command line zipping so I started looking for...
12
Nepomuk
by: Nepomuk | last post by:
Hi! I want to have my program delete some folders including all contents. For that, I wrote this method: private static void delete(String source) { File tmp = new File(source);...
1
by: =?Utf-8?B?UVNJRGV2ZWxvcGVy?= | last post by:
Using .NET 2.0 is it more efficient to copy files to a single folder versus spreading them across multiple folders. For instance if we have 100,000 files to be copied, Do we copy all of them to...
6
by: chrisbirk | last post by:
Hi! I want to write an application on windows xp, which iterates n times a model script (exe) and copies every single run the results (multiple files such as text, maps, subfolders,etc) from the...
2
by: Benjamin Watine | last post by:
Hi, I'm about to develop a small python application and I wonder how to organize files in this application. I'm familar to java, so I'm tempted to use the same convention : 1 file per class and...
0
by: Gabriel Genellina | last post by:
En Fri, 05 Sep 2008 12:53:12 -0300, Benjamin Watine <watine@cines.fr> escribió: You don't *have* to artificially restrict yourself to one class per file. In Python it's common to place several...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.