How to zip a whole catalog with Java?

can you tell me how to zip a whole catalog?
i am not able to find a method that can zip a whole catalog and the files in it.
please help me,thanks

The following program is an extension of the code posted at:
http://forum.java.sun.com/thread.jsp?forum=31&thread=48084
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream ;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.Date;
public class NZipCompresser {
   private String m_basePath=null;
   private File m_dir = null;
   private String m_OutputFileName;
   public static void main(String[] args) {
      File directory=new File(args[0]);
      new NZipCompresser(directory, args[1]);
   public NZipCompresser() {
   // This class gets directory and compress it reqursivelyinto zip file named outputFileName
   public NZipCompresser(File directory,String outputFileName) {
      m_dir = directory;
      m_OutputFileName = outputFileName;
      try {
         compress();
      } catch (Throwable e) {}
   public void compress () throws Exception {
      try {
         FileOutputStream zipFilename = new FileOutputStream(m_OutputFileName) ;
         ZipOutputStream zipoutputstream = new ZipOutputStream (zipFilename);
         m_basePath = m_dir.getPath();
         CompressDir (m_dir,zipoutputstream);
         zipoutputstream.setMethod(ZipOutputStream.DEFLATED);
         zipoutputstream.close();
      catch (Exception e) {
         throw new Exception ("Something wrong in compresser: " + e);
   public void setDirectory (File dir) {
      m_dir = dir;
   public void setOutputFileName (String FileName) {
      m_OutputFileName = FileName;
   public File getDirectory () {
      return m_dir;
   public String getOutputFileName () {
      return m_OutputFileName;
   //Walker through directory structure
   private void CompressDir (File f, ZipOutputStream zipoutputstream) {
      System.out.println(f);
      if (f.isDirectory()) {
         File [] files = f.listFiles();
         for (int j=0;j<files.length;j++) {
            if (files[j].isDirectory()) {
               System.out.println("calling CompressOneDir with:"+files[j].getPath());
               CompressDir (files[j],zipoutputstream);
            if (files[j].isFile()) {
               System.out.println("adding file:" +  files[j].getPath());
               addOneFile(files[j],zipoutputstream);
      System.out.println("exiting:"+f);
   //Actualy compress the file
   private void addOneFile (File file, ZipOutputStream zipoutputstream) {
      ZipEntry zipentry = new ZipEntry(file.getPath().substring(m_basePath.length()+1));
      FileInputStream fileinputstream;
      CRC32 crc32 = new CRC32();
      byte [] rgb = new byte [1024];
      int n;
      //Compute CRC of input stream
      try {
         fileinputstream = new FileInputStream(file);
         while ((n = fileinputstream.read(rgb)) > -1) {
            crc32.update(rgb, 0, n);
         fileinputstream.close();
      catch (Exception e) {
         System.out.println("Error in computing CRC:");
         e.printStackTrace();
      //Set Up Zip Entry
      zipentry.setSize(file.length());
      zipentry.setTime(file.lastModified());
      zipentry.setCrc(crc32.getValue());
      //Write Data
      try {
         zipoutputstream.putNextEntry(zipentry);
         fileinputstream = new FileInputStream(file);
         while ((n = fileinputstream.read(rgb)) > -1) {
            zipoutputstream.write(rgb, 0, n);
         fileinputstream.close();
         zipoutputstream.closeEntry();
      catch (Exception ex) {
         System.out.println("Error in writing data:");
         ex.printStackTrace();
}Compile this program and run it as follows:
java NZipCompresser directory_name zipOutput_name
Is this what you're looking for?
V.V.

Similar Messages

  • How do I compress a string with  java.util.zip - not a file ?

    How do I compress a string with java.util.zip?
    Is possible to compress something else except a file?

    Of course, compression works on bytes, not some higher level constructs like Strings or files.
    You can use the ZipOutputStream or DeflaterOutputStream for compression.
    And the javadoc for Deflater even has a code example of compressing a String.
    Edited by: Kayaman on May 22, 2011 5:04 PM

  • How to use a progress bar with java mail?

    Hi, i'm new here.
    I want if someone can recommend me how to show a progress bar with java mail.
    Because, i send a message but the screen freeze, and the progress bar never appear, after the send progress finish.
    Thanks

    So why would the code we post be any different than the code in the tutorial? Why do you think our code would be easier to understand? The tutorial contains explanations about the code.
    Did you download the code and execute it? Did it work? Then customize the code to suit your situation. We can't give you the code because we don't know exactly what you are attempting to do. We don't know how you have changed to demo code so that it no longer works. Its up to you to compare your code with the demo code to see what the difference is.

  • How to ZIP a PDF File with a Password Protection

    Hi,
    i've a pdf file with created smartforms and i want to assign a password to that pdf file but the SAP doesn't let doing that protection. So i want to create a zip file with a password protection for PDF file.
    How can i create a zip file with a password protection? Can somebody help me please?
    Thanks.

    Hello,
    Check this links
    Take a look to the class CL_ABAP_GZIP
    open (top-)zip-archive
    CALL METHOD lo_zip->load
        EXPORTING
          zip             = lv_zip_file_head
        EXCEPTIONS
          zip_parse_error = 1
          OTHERS          = 2.
    create sub-zip-archives which contain the files you would assign to a folder
    add sub-zip-archive to top-zip-archive
    CALL METHOD lo_zip->add
         EXPORTING
            name    = lv_zip_filename
            content = lv_zip_file.
    save zip-archive
    CALL METHOD lo_zip->save
        RECEIVING
          zip = ev_zip_file.
    ABAP Development
    How to ZIP a PDF file email attachment
    Re: How to ZIP a PDF file email attachment

  • How to create a SAS Dataset with Java

    Hello All,
    The subject line says it all. Does anyone out there know how to create a SAS Dataset using Java? I Googled it and searched here with no luck.
    Thanks
    KP

    Some parts of SAS appear to have been exposed via a Java API through this product:
    http://support.sas.com/rnd/app/da/workshop/faq.html
    Hope that helps
    Lee

  • C++ can send a "struct" over TCP.How to do the same fuction with JAVA?

    as Title~
    C++ send a struct like the following...
    NEO_MSG neo_msg;
    struct NEO_MSG
    int iPortRecv; // port for recv data of client
    char verify;
    ////After create a TCP connection....
    send(ServerSock, (char*)&neo_msg, sizeof(neo_msg), 0);
    How to rewrite it with JAVA?

    If you are trying to do it in a way that is compatible with C++, then you'll need to write the bytes to the socket. You can do this by wrapping the socket's output stream with a DataOutputStream, then writing each value in order.
    Remember that a C++ struct is just a convention of accessing a linear array of bytes, so the above is equivalent.
    If you are just trying to send an Object's data over a socket (to another Java app), then you can wrap the socket's output stream with an ObjectOutputStream, then just write the object to it.
    - K

  • How to call a C method with Java

    Hi all,
    is it possible calling a C method with Java?? And how to...?
    thx for helping
    Cobol1

    is it possible calling a C method with Java?? And how to...?Not in general no.
    You can use JNI which will call another C function (which you write) and which then calls your C method.
    If the method is of a specific type (like OLE, Corba) then there are packages available which can allow you to access it. They still use JNI underneath, but hide that functionality from you.

  • How to use the Rc4DLL.dll with java (jre1.4 )

    I am not able to use Rc4DLL.dll with java, there are some characters (encrypted using Rc4DLL.dll) that java is not able to identify. So while decrypting in java using Rc4DLL I am not getting the desired output (as some character java tries to decrypt are not supported with java). Could some one give a solution of using Rc4DLL with java jre 1.4

    RC4 cipher is supported by 1.4.
    And surely you can turn a link to the 1.5.0 JCE Reference Guide into a link to the 1.4.2 Reference Guide? I did. Took me 5 seconds to check that. As opposed to wasting a day and a half in forums like you just did.

  • How to validate the Xml File With Java

    Hi,
    Can pls tell me. I want to validate the XML File for the Some Mandartory TAG. if that if Tag null i want to generate error xml file with error and i want move another folder with java. pls help me as soon as possible

    Use a validating parser (any recent Xerces, for one) and switch on the validation feature. Very much vendor-specific, so look at the docs of your parser. Oh, you do have a schema for these documents, don't you?

  • A Problem about zip a Chinese File with Java Zip package

    Hi,
    my problem is following:
    I use "Java(1.3.1_02) Zip package" to compress some files into a zip File
    all thing is smooth except one:(
    If there is a fileName with Chinese (big5 encoding) characters
    it doesen't work!
    Can anyone tell me how to do?
    Thanks a lot!

    Hi !
    i do have a problem relating with the different character(korean).Hope u must be working with chinese characters.My problem is while displaying the korean characters from database , the characters are broken and not able to display on jsp pages.....
    Hope u can understand my problem.....
    Thanks....

  • How to login to eBay programmatically with Java

    Hi,
    I'm trying to write a Java program that can handle logging in to eBay in order to retrieve certain user-specific information, for example My eBay, or list of items with email address. The way I've done is like this:
    Retrieve (HTTP GET) the initial page at http://cgi1.ebay.com/aw-cgi/eBayISAPI.dll?MyEbayLogin. Then capture all the cookies. The resulting HTML page has a form with some <input...> fields in there. So I concatenate all these <input...>, then send a HTTP POST to the URL on that form together with the concatenated parameters. For some reason, the resulting HTML page is back at http://cgi1.ebay.com/aw-cgi/eBayISAPI.dll?MyEbayLogin
    I've pretty sure I've handled the cookies alright, because when I leave out the cookies, I'll get a "Cookies Rejected" HTML page. I've also been able to log in to hotmail in similar fashion, so I think most (if not all) technical details are ok. These are the calls I made (among others):
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    conn.setAllowUserInteraction(false);
    conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded" );
    conn.setInstanceFollowRedirects(false);
    conn.setUseCaches(false);
    conn.setRequestProperty("Cookie", cookie);
    My question is, has anyone succeeded in logging into eBay using Java, and if so could you share how you've done it (like, is there anything special to be done?). I'm asking this because when logging to hotmail.com, there were some twists that I had to look into (in javascript code) before the thing works. But I can't see anything similar in the eBay login page.
    Alternatively, is there away to intercept and peek into HTTP requests sent by IE? I have Ethereal but it's at protocol level only (I think), not HTTP messages/requests. I figure if I can read these requests that IE makes when it logs in, I can try applying the same behaviour (simulate) in my Java code.
    Many thanks!

    Right after I posted this, I tried again in desperation and guess what, it already works! It turns out that I was just impatient, the second time the page http://cgi1.ebay.com/aw-cgi/eBayISAPI.dll?MyEbayLogin is returned, you just have to retrieve it again, this time using the cookies that you got from previous log in. Keep going like that (when you see a 3xx Redirect code) and you'll get to your My eBay page eventually.
    Anyway, these are the pages that I access in case anyone is attempting to do the same thing:
    1. Use HTTP GET on http://cgi1.ebay.com/aw-cgi/eBayISAPI.dll?MyEbayLogin, get a 302 (Moved) header with location=http://signin.ebay.com/aw-cgi/eBayISAPI.dll?SignIn&UsingSSL=0&pUserId=&ru=http%3A%2F%2Fcgi1.ebay.com%2Faw-cgi%2FeBayISAPI.dll%3FMyEbayLogin&pp=pass&co_partnerid=2&pageType=174&i1=0 (Let's call this page 1a)
    2. Use HTTP GET on page 1a, get a HTML content page (with login form) and 2 cookies.
    3. Use HTTP POST to send form data to the URL in the login form (which is http://signin.ebay.com/aw-cgi/eBayISAPI.dll), remember to send all cookies as well. (Also this is provided you have an eBay account, the form will ask for username and passwd). Get back a 302 (Moved) with Location=http://cgi1.ebay.com/aw-cgi/eBayISAPI.dll?MyEbayLogin, and 7-8 cookies. Store all these cookies.
    4. Use HTTP GET to access http://cgi1.ebay.com/aw-cgi/eBayISAPI.dll?MyEbayLogin , again remember to send all the cookies. Get back 302 (Moved) with Location=http://cgi1.ebay.com/aw-cgi/ebayISAPI.dll?MyEbayItemsBiddingOn&userid=xxxxxxxxxxx&pass=xxxxxxxxxxxxxx&first=N&sellerSort=3&bidderSort=3&watchSort=3&dayssince=2&p1=0&p2=0&p3=0&p4=0&p5=0&ssPageName=MerchMax (Let's call this page 4a)
    5. Finally! Use HTTP GET to access page 4a and you're at the "My Ebay" page.
    After manually going through all this, you'll appreciate how much work the browser does each time it logs in to something. Also if you're planning to do this, it may save time in the long run to create a rudimentary browser that can display and handle the cookies automatically, (and takes care of form data too).

  • How do i recompile whole system with glibc and gcc from test

    I always run testing and hence upgraded all my system a couple of days back. How ever one pprogram i use very often, BLENDER isn't working after i upgraded glibc and gcc4. I have recompiled it but when I get all this errors when i start it http://bbs.archlinux.org/viewtopic.php?t=21825.
    I think i need to rcompile all its dependant programs with new glibc and gcc from testing also. Problem is I dentifying which programs to compile is proving a pain as the dependant programs also depend on other programs etc...
    Is there a way to recompile my whole system without having to do it one by one?

    if you want to compile everything, gentoo is an option. But abs is excellent too.
    P.S. Gentoo's compilation drove me out of it

  • How to root out memory leak with  Java JNI & Native BDB 11g ?

    We are testing a web application using the 32-bit compiled native 11g version of BDB (with replication) under 32-bit IBM 1.5 JVM via JNI under 64-bit RedHat Linux. We are experiencing what appears to be a memory leak without a commensurate increase in Java heap size. Basically the process size continues to grow until the max 32-process size is reached (4Gb) and eventually stops running (no core). Java heap is set to 2Gb min/max. GCs are nominal, so the leak appears to be native and outside Java bytecode.
    We need to determine whether there is a memory leak in BDB, or the IBM JVM or simply a mis-use of BDB in the Java code. What tools/instrumentation/db statistic should be used to help get to root cause? Do you recommend using System Tap (with some particular text command script)? What DB stats should we capture to get to the bottom of this memory leak? What troubleshooting steps can you recommend?
    Thanks ahead of time.
    JE.
    Edited by: 787930 on Aug 12, 2010 5:42 PM

    That's troublesome... DB itself doesn't have stats that track VM in any useful way. I am not familiar with SystemTap but a quick look at it seems to imply that it's better for kernel monitoring than user space. It's pretty hard to get DB to leak significant amounts of memory. The reason is that it mostly uses shared memory carved from the environment. Also if you are neglecting to close or delete some object DB generally complains about it somewhere.
    I don't see how pmap would help if it's a heap leak but maybe I'm missing something.
    One way to rule DB out is to replace its internal memory allocation functions with your own that are instrumented to track how much VM has been allocated (and freed). This is very easy to do using the interfaces:
    db_env_set_func_malloc()
    db_env_set_func_free()
    These are global to your process and your functions will be used where DB would otherwise call malloc() and free(). How you get usage information out of the system is an exercise left to the reader :-) If it turns out DB is the culprit then there is more thinking to do to isolate the problem.
    Other ideas that can provide information if not actual smoking guns:
    -- accelerate reproduction of the problem by allocating nearly all of the VM to the JVM and the DB cache (or otherwise limit the allowable VM in your process)
    -- change the VM allocated to the JVM in various ways
    Regards,
    George

  • How do I resolve connection error with Java API listener?

    I have created a listener using the new Java API (see How do I implement a listener using new MDM Java API? for background). When I run it, I get this error message
    Mar 19, 2008 3:57:58 PM com.sap.mdm.internal.net.ConnectionImpl finalize
    INFO: Disconnect was not called. Cleaning up connection in finalize.
    This message is triggered whenever I generate a data event that I would otherwise expect to be captured and handled by the listener. I have tried a number of things, including setting the connection to NO_TIMEOUT and trying SimpleConnection versus ConnectionPool, but always with the same result.
    Here is some sample code for the listener:
    public class DataListenerImpl implements DataListener {
         public void recordAdded(RecordEvent evt) {          
              System.out.println("===> Record Added Event");
              System.out.println(evt.getServerName());
         public void recordCheckedIn(RecordEvent evt) {
              System.out.println("===> Record Checked In Event");
              System.out.println(evt.getServerName());          
         public void recordCheckedOut(RecordEvent evt) {
              System.out.println("===> Record Checked Out Event");
              System.out.println(evt.getServerName());               
         public void recordModified(RecordEvent evt) {
              System.out.println("===> Record Modified Event");
              System.out.println(evt.getServerName());
    And here is the code for the Event Dispatcher:
    public void execute(Repository repository) {
         DataListener listener = new DataListenerImpl();
         try {
              EventDispatcherManager edm = EventDispatcherManager.getInstance();
              EventDispatcher ed = edm.getEventDispatcher(repository.getServer().getName());
              ed.addListener(listener);
              ed.registerDataNotifications(SystemProperties.getUserName(), SystemProperties.getPassword(),
                        repository.getIdentifier(), repository.getLoginRegion());
              ed.registerRepositoryNotifications(SystemProperties.getUserName(), SystemProperties.getPassword(),
                        repository.getIdentifier());
              ed.registerGlobalNotifications();
              while (true) {
                   Thread.yield();
                   try {
                        Thread.sleep(1500);
                   } catch (InterruptedException ex) {
                        System.out.println("Interrupted Exception: " + ex.getMessage());
         } catch (ConnectionException e) {
              e.printStackTrace();
         } catch (CommandException e) {
              e.printStackTrace();
    Has anyone else encountered this message? Could it be related to a TCP configuration on the server? Or is this a bug in the Java API?
    As I mentioned in the forum posting linked to above, I have not encountered this problem with the MDM4J API.
    Any help is greatly appreciated.

    I resolved it. We are switching over to SP6, Patch 1 and the listener code works fine with this version of the Java API.
    Just one thing to note, though: make sure that you register data notifications through MetadataManager in your initialization code:
    metadataManager.registerDataNotifications(userSessionContext, repositoryPassword);
    For information on the changes to the SP6 Java API, especially with regard to connecting to MDM with the UserSessionContext, please review Richard LeBlanc's [presentation|https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/20073a91-3e8b-2a10-52ae-e1b4a10add1c].

  • How to link OS timezone name with java zi

    Hi all,
    I need to add some timezone definition in some (HP-UX) server to define DST rules for Iraq.
    The zone information already exists in java with "Asia/Baghdad" timezone name.
    How does java link the OS timezone found in tztab (e.g. MET-1METDST) with its ZoneInfo id file (e.g. "Europe/Paris")
    This is what I'm looking for to link my tztab with zi files.
    thanks
    antonio.

    Download and set up Shareway IP, and use Ethernet to transfer files.
    (24219)

Maybe you are looking for

  • Thoroughly disappointed with Droid Razr

    I paid a premium price less than a year ago for a LEMON of a phone -- the Droid Razr by Motorola.  I have now replaced by new phone with three (3) refurbished phones because of the faculty Google operating system and poor manufacturing by Motorola, w

  • HP ENVY m6 Notebook PC trackpad issue even after HP repair

    2 weeks ago i sent my HP ENVY m6 Notebook to the HP Repair center because i was having major issues with the trackpad. It would not move fluidly,and click, and move on its own. I received my laptop back today anticipating that everything would work p

  • What is the disadvantage of using hints in query

    hi all, i am report developer, in my project we were using hits in the query ... so that the query performance has improved .. my question is if we use hints in the query will it give any effects.. means to say instead of using hints we can make use

  • Wired keyboard and mouse

    I am interested in buying a wired keyboard and mouse with the Apple cinema display. I am in Korea. I went to the Apple site and it just advertises the wireless versions. I do not like wireless versions because I do not like to mess around with batter

  • How to get a factory unlocked iphone 4S in India

    I want to get a factory unlocked iphone 4S. I am from india and here we dont get it factory unlocked , we get these models with carrier airtel and aircel can any one suggest/help me