473,624 Members | 2,290 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

COmpressing files and folders in Java

7 New Member
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!!!]

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 3223
JosAH
11,448 Recognized Expert MVP
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
msankardas
7 New Member
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
msankardas
7 New Member
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
1883
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 parallel computation. Key Benefits of SocketPro: Super performance and scalability It is a guarantee that SocketPro based client-server applications
1
1761
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 9i database using a BLOB column. I have read in the file using a file stream and then put it in a byte array. The problem is that I need to compress the byte array before inserting into the database. I have tried to use ZLIB, but I cannot get...
6
2102
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, ' '.join(source)) I execute this using os.command(zip_command). It works fine... But when I run this script in Windows XP, I get an error while
4
1722
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 alternatives. I found some modules in Perl which does zipping. I guess it goes by the name 'gzip'. I plan to write the zipping feature in Perl and import it into Python.
12
2435
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); if(tmp.isDirectory() && tmp.list().length > 0) { System.out.print("** Directory: " + tmp.getName()); String list = tmp.list();
1
3880
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 a single folder called 'All Files' Do we spread them out and copy them to multiple folders like Folder 000 - Copy files from 0 to 1000 Folder 001 - Copy files from 1000 to 2000 Folder 002 - Copy files from 2000 to 2999
6
2404
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 existing folder into a new one. The code works, but no files nor folders are copied. This is how far as I got being an absolute beginner in Java. Thanks for any help, CB import java.io.*; public class PCRmain { public static void...
2
977
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 1 folders per package. I know that packages doesn't exists in python, they are modules instead. May I create specific module for each "group of class" ? My application follow the MVC paradigm, so basically, I've a package Model, a package
0
967
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 related classes in the same module (i.e., file). You don't have to write so much boilerplate code as in Java, so classes tend to be smaller in size; you may even find classes with an empty body.
0
8681
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8629
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8341
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8488
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7170
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6112
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5570
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4084
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1793
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.