Writing to a Zip File

Hello, anyone that can help with this would be greatly appreciated.
As of right now I am writing to a file line by line from a vector. I would like to write a zip file instead. I would like to eliminate writing to the file (at a certain path) and just create a zip file instead and write to it line by line.
Is this possible?
I think it is but I was not real clear on the
zipoutputstream.write(this stuff).
Thank you.

Got it to write to the zip file.

Similar Messages

  • Writing objects with in zip files

    Hi,
    I am trying to write an object into a zip file :
    ZipOutputStream zout=new ZipOutputStream(new FileOutputStream("test.zip");
    ZipEntry ze=new ZipEntry("test.dat");
    zout.putNextEntry(ze);
    ObjectOutputStream out=new ObjectOutputStream(zout);
    out.writeObject(obj);
    out.close();
    zout.closeEntry();
    zout.close();
    The above code is within a try-catch block.
    It is compiling correctly.
    But it is throwing an exception just after executing "zout.closeEntry()".
    The exception is "java.io.Exception: Stream Closed".
    I am using JDK 1.3.
    Can anyone help me.
    Indra.

    Hi Indra,
    I'm sorry it didn't work. I would try to simulate that problem but I really don't have time right now (but I will).
    What you can do is to try to create that zip file in 2 steps, first just serialize the objects in a ordinary file and then read from that file and create a zip file. Of course you'll have to do the same to get your objects out from the zip file.
    If the file is not too big you can use a ByteArrayOutputStream instead of a FileOutputStream for the first file.
    hope it will work,
    Gabe

  • Reading a Compressed File from a ZIP File, which is an entry of ZIP File

    Hello, Experts,
    Would it be possible somebody to help me with code example for the following problem?
    I want to read a compressed file from a ZIP file, which is an entry of ZIP File, without extacting/writing files on file system. Is this possible?
    Lets say we have a ZipFile1. There is ZipFile2 inside ZipFile1. And inside ZipFile2 is FileA. The scenario is reading FileA without extracting on file system.
    Thank you in advance for your help.
    Cheers
    RADY

    The classes you want to be using are java.util.zip.ZipInputStream and and ZipEntry from the same package. Construct the ZipInputStream with the input you have for the outer zip. Loop with ZipInputStream.getNextEntry until you find the inner zip you're looking for - that method returns a ZipEntry, and you get the name of the zip entry with ZipEntry.getName. Read the ZipInputStream from that point into some buffer, and read that buffer into a new ZipInputStream - rinse and repeat until you have the contents of the file in the zip in the zip...

  • Name zip file and zipped file in File Receiver

    Dear experts,
    I have a "RFC to File"-scenario. So I have a File Receiver and the received XML needs to be zipped. I have a XSLT mapping that hands over a dynamic file name to the File Receiver. Now when I use the PayloadZipBean my resulting ZIP-file gets the dynamic name. But the zipped XML gets the name "untitled.xml". But I also want the zipped file to get the dynamic name!
    I had a look at Stefan Grube's blog /people/stefan.grube/blog/2007/02/20/working-with-the-payloadzipbean-module-of-the-xi-adapter-framework
    and also at the WIKI http://wiki.sdn.sap.com/wiki/display/XI/Adapter%20Module%20PI%207.0%20Set%20Attachment%20Name?bc=true
    Do you know if there is any way I can avoid writing my own adapter module? I would like to stay with SAP standard modules!
    If not, will the module described in that WIKI also work with a File Receiver instead of a Mail Receiver? (I think it should)
    Thank you for any ideas and best regards,
    Peter

    Hello Amit, Hello Abhishek Salvi,
    Thank you again for your advice and the links to the NWDS. I downloaded it and everything went well until the deployment.
    I followed How-to-Guide: http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/c0b39e65-981e-2b10-1c9c-fc3f8e6747fa?quicklink=index&overridelayout=true
    Then I got the error: The DOCTYPE declaration in the ejb-jar.xml deployment descriptor is missing.
    I looked at thread: The DOCTYPE declaration in the ejb-jar.xml deployment descriptor is missing
    I am using PI 7.0, JDK version 1.4.12.
    My local JDK Version 1.5.0_22, NWDS 7.1.
    Could the JDK version on the server be a problem? Or NWDS 7.1 and PI 7.0?
    I used all the libraries mentioned on this page under PI 7.0:
    http://wiki.sdn.sap.com/wiki/display/XI/Where%20to%20get%20the%20libraries%20for%20XI%20development
    When I create the Enterprise Bean I have to specify "Component and Local Interfaces", e.g. "com.sap.aii.af.lib.mp....."
    But in my PI system I cannot find JAR files with the name "aii.af.lib.mp..."
    Could that be the problem?
    Do I have to specify different "Component and Local Interfaces" when creating the Enterprise Bean?
    Thank you again for any help!
    Best regards,
    Peter
    Edited by: Peter Wallner on Apr 21, 2011 10:13 AM

  • Sending Downsized Images to Zip File Problems

    I use Adobe Elements 5.0 and have been uploading images to the organizer for a couple of years without problems, until just recently.  Here is how the process used to work.  When images are uploaded they are saved to a new file folder under C drive/ Public Photos/ specific folder with date and subject matter;  I fix the images in adobe then go to the specific folder and create a subfolder within that folder called "downsized".  I then use Adobe to "process multiple files" and downsize for purposes of sending to Pbase. Once the files have been downsized the images end up in the specifc folder, inside the downsized subfolder.  I then rt click and select "send to" 'compressed (zip) folder'.  From there I would open Pbase and upload the zipped folder to a new gallery.
    Recently everything has been fine until I get to the send to zip folder.  Instead of sending to the familiar yellow zip folder it is being sent to the adobe photoshop editor in the form of the adobe icon.  I click on that and it promts me for filename, width, height, resolution and color mode.  I am unable to upload this zipped file version to Pbase.  Previously, when things were operating correctly, I would have a folder, with a subfolder under that called downsized.  Within the downsized folder would be the zipped file for sending to Pbase.  Something has happened recently so that I am ending up with a folder, a subfolder called downsized a sub 'folder' under that which is the adobe elements icon and a downsized file under that which is a copy of the downzied photos in the first downsized file.  In checking out all of my 100 or so folders all of them have been 'converted" to the same organization pattern.  What has happened and how do I fix the problem so that I can send the downsized folder to a zip file for importing to Pbase?  Thank you. 

    You should realize I am just making wild guesses at your problem. And I am assuming you actually have a Microsoft Word document that you are sending. If you do, then following menu options "Insert, Picture, From File..." should work. But if you are just writing out HTML and telling the browser it's actually a Word document, I have no idea.

  • Adding a file into existing zip file

    I need a add a file into existing zip file. and write into printwriter.
    How to do it?
    Waiting for the reply.
    Thanks and Regards,
    Narayanan. G

    Narayanan.G wrote:
    I need a add a file into existing zip file.API: [ZipOutputStream#putNextEntry()|http://java.sun.com/javase/6/docs/api/java/util/zip/ZipOutputStream.html#putNextEntry%28java.util.zip.ZipEntry%29]
    Tutorial: [http://java.sun.com/developer/technicalArticles/Programming/compression/].
    and write into printwriter.Writing a zip file into printwriter? Huh? Please elaborate.

  • Getting a StackOverflowError trying to download big content sync zip file

    We've noticed this happens when trying to download a big Content Sync zip file (typically of around 280MB, although recently we saw the same issue with a 250MB file, so we're not sure of the root cause of this).
    The only prerequisite to reproduce this issue is to configure your content sync to have > 250MB of content (in the form of images, html, js, etc).  The steps to reproduce are the following:
    Navigate to the content sync console URL: /libs/cq/contentsync/content/console.html
    Click on the 'Clear Cache' button.
    Click on the 'Update Cache' button.  No problems up to here, content sync cache (under /var/contentsync) is populated with expected assets and files.
    Click on the 'Download Full' button.  Almost immediately, the app crashes with the following stack trace:
    02.05.2013 00:56:14.248 *ERROR* [204.90.11.3 [1367455869892] GET /etc/contentsync/audiusa-retail.zip HTTP/1.1] org.apache.sling.engine.impl.SlingRequestProcessorImpl service: Uncaught Throwable java.lang.StackOverflowError
            at org.apache.commons.collections.map.AbstractReferenceMap.isEqualKey(AbstractReferenceMap.j ava:434)
            at org.apache.commons.collections.map.AbstractHashedMap.getEntry(AbstractHashedMap.java:436)
            at org.apache.commons.collections.map.AbstractReferenceMap.getEntry(AbstractReferenceMap.jav a:405)
            at org.apache.commons.collections.map.AbstractReferenceMap.get(AbstractReferenceMap.java:230 )
            at org.apache.jackrabbit.core.state.ItemStateReferenceCache.retrieve(ItemStateReferenceCache .java:147)
            at org.apache.jackrabbit.core.state.LocalItemStateManager.getItemState(LocalItemStateManager .java:171)
            at org.apache.jackrabbit.core.state.XAItemStateManager.getItemState(XAItemStateManager.java: 260)
            at org.apache.jackrabbit.core.state.SessionItemStateManager.getItemState(SessionItemStateMan ager.java:161)
            at org.apache.jackrabbit.core.ItemManager.getItemData(ItemManager.java:382)
            at org.apache.jackrabbit.core.ItemManager.getItem(ItemManager.java:328)
            at org.apache.jackrabbit.core.ItemManager.getItem(ItemManager.java:622)
            at org.apache.jackrabbit.core.LazyItemIterator.prefetchNext(LazyItemIterator.java:122)
            at org.apache.jackrabbit.core.LazyItemIterator.<init>(LazyItemIterator.java:104)
            at org.apache.jackrabbit.core.LazyItemIterator.<init>(LazyItemIterator.java:85)
            at org.apache.jackrabbit.core.ItemManager.getChildProperties(ItemManager.java:816)
            at org.apache.jackrabbit.core.NodeImpl$10.perform(NodeImpl.java:2178)
            at org.apache.jackrabbit.core.NodeImpl$10.perform(NodeImpl.java:2174)
            at org.apache.jackrabbit.core.session.SessionState.perform(SessionState.java:216)
            at org.apache.jackrabbit.core.ItemImpl.perform(ItemImpl.java:91)
            at org.apache.jackrabbit.core.NodeImpl.getProperties(NodeImpl.java:2174)
            at javax.jcr.util.TraversingItemVisitor.visit(TraversingItemVisitor.java:202)
            at org.apache.jackrabbit.core.NodeImpl.accept(NodeImpl.java:1697)
            at javax.jcr.util.TraversingItemVisitor.visit(TraversingItemVisitor.java:219)
            at org.apache.jackrabbit.core.NodeImpl.accept(NodeImpl.java:1697)
            at javax.jcr.util.TraversingItemVisitor.visit(TraversingItemVisitor.java:219)
            at org.apache.jackrabbit.core.NodeImpl.accept(NodeImpl.java:1697)
            at javax.jcr.util.TraversingItemVisitor.visit(TraversingItemVisitor.java:219)
            at org.apache.jackrabbit.core.NodeImpl.accept(NodeImpl.java:1697)
            at javax.jcr.util.TraversingItemVisitor.visit(TraversingItemVisitor.java:219)
    We've extended the content sync framework by writing 2 ContentUpdateHandler implementations.  Given that the content update process finishes correctly, we dont' think this is the root cause of the problem.
    Any help on this subject is appreciated.
    Thanks,
    -Daniel

    Hi Daniel,
        File daycare with steps to reproduce, logs, thread dump & hs_err file.
    Thanks,
    Sham
    @adobe_sham

  • Zip file Mail attachment download in ios 7

    Hi
    I have downlaoded a zip file attachment from my Mail in ios 7 on Iphone. I am not able to locate the location of the file.
    Please help me in locating the file.
    Thanks

    Hi,
    as I found this in wikipedia:
    Another common problem is the use of '\n' when communicating using an Internet protocol that mandates the use of ASCII CR+LF for ending lines. Writing '\n' to a text mode stream works correctly on Windows systems, but produces only LF on Unix, and something completely different on more exotic systems. Using "\r\n" in binary mode is slightly better, as it works on many ASCII-compatible systems, but still fails in the general case. One approach is to use binary mode and specify the numeric values of the control sequence directly, "\x0D\x0A".
    Back to my issue:
    In the UDF I am adding "\r\n" but only the "\n" seems to survive!
    In Mapping test line feeds are available and the lines are shown as expected.
    Using Notepad ++ to open the created txt file from the mail shows that LF is in the file at each end of line but CR is missing.
    CR is only at the end of the last line in the file and is not from the UDF that creates the mail or the UDF that creates the attachment lines. Seems that this is added somewhere else behind the mapping.
    This is what I found in galileo computing
    (http://www.galileocomputing.de/glossar/gp/anzeige-11241/FirstLetter-Z, SORRY, only available in german language!):
    In Parsing of XML-Documents the XML-Parser changes the end of line delimiter internally in general to a simple line feed (LF, #0A) as usual in UNIX. ..... In Windows this could result in problems with readability of  source texts (e.g. in Notepad) which can be solved by choosing the right editor.
    My target application is on Windows and not able to "choose" the right editor (PI system is on windoes OS too) !
    But Im wondering where the CR at the end of the text comes from when all the \r\n will be replaced with \n as described.
    Ideas are really welcome!
    Best regards
    Dirk
    Edited by: Meinhard Dirk on May 31, 2011 2:45 PM

  • Cannot use winzip to unzip the zip file zipped by java.util.zip

    Hi all,
    I use the followcode to create a zip file, and i downlaod it and try to use winzip to unzip this file but fail. The path is correct and i got the zip file. but it just cannot unzip.
    pls help
    thanks alot.
    Kin
              int count = 0;
              count = ContentDocuments.size();
              for (int i = 0; i < bb; i++)     {
                   System.out.println(filenames[i] + "");
              // Create a buffer for reading the files
              byte[] buf = new byte[10*1024*1024];
              try {      
                   String outFilename = MyDir + "zipfile/" + getContentID2()+".zip";
                   System.out.println("outFilename = " + outFilename);
                   ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
                   for (int i=0; i<filenames.length; i++) {           
                        FileInputStream in = new FileInputStream(filenames);
                        out.putNextEntry(new ZipEntry(filenames[i]));
                        int len;
                        while ((len = in.read(buf)) != -1) {               
                             out.write(buf, 0, len);
                        out.closeEntry();
                        in.close();
                   out.close();
              } catch (IOException e)     {
                   System.err.println("zipprocess " + e.getMessage());

    I've written a replacement zip file creator class. Not much tested but it seems to work, however I've yet to try it with the version of WINZIP that rejected my previous attempts. Oh, and the stored dates are garbage.
    * ZipOutputFile.java
    * Created on 25 March 2004, 13:08
    package zip;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    * <p>Creates a ZIP archive in a file which WINZIP should be able to read.</p>
    * <p>Unfortunately zip archives generated by the standard Java class
    * {@link java.util.zip.ZipOutputStream}, while adhering to PKZIPs format specification,
    * don't appear to be readable by some versions of WinZip and similar utilities. This is
    * probably because they use
    * a format specified for writing to a non-seakable stream, where the length and CRC of
    * a file is writen to a special block following the data. Since the length of the binary
    * date is unknown this makes an archive quite complicated to read, and it looks like
    * WinZip hasn't bothered.</p>
    * <p>All data is Deflated. Close completes the archive, flush terminates the current entry.</p>
    * @see java.util.zip.ZipOutputStream
    * @author  Malcolm McMahon
    public class ZipOutputFile extends java.io.OutputStream {
        byte[] oneByte = new byte[1];
        java.io.RandomAccessFile archive;
        public final static short DEFLATE_METHOD = 8;
        public final static short VERSION_CODE = 20;
        public final static short MIN_VERSION = 10;
        public final static int  ENTRY_HEADER_MAGIC = 0x04034b50;
        public final static int  CATALOG_HEADER_MAGIC = 0x02014b50;
        public final static int  CATALOG_END_MAGIC = 0x06054b50;
        private final static short DISC_NUMBER = 0;
        ByteBuffer entryHeader = ByteBuffer.wrap(new byte[30]);
        ByteBuffer entryLater = ByteBuffer.wrap(new byte[12]);
        java.util.zip.CRC32 crcAcc = new java.util.zip.CRC32();
        java.util.zip.Deflater def = new java.util.zip.Deflater(java.util.zip.Deflater.DEFLATED, true);
        int totalCompressed;
        long MSEPOCH;
        byte [] deflateBuf = new byte[2048];
        public static final long SECONDS_TO_DAYS = 60 * 60 * 24;
         * Entry stores info about each file stored
        private class Entry {
            long offset;        // position of header in file
            byte[] name;
            long crc;
            int compressedSize;
            int uncompressedSize;
            java.util.Date date;
             * Contructor also writes initial header.
             * @param fileName Name under which data is stored.
             * @param date  Date to label the file with
             * @TODO get the date stored properly
            public Entry(String fileName, java.util.Date date) throws IOException {
                name = fileName.getBytes();
                this.date = date == null ? new java.util.Date() : date;
                entryHeader.position(10);
                putDate(entryHeader);
                entryHeader.putShort(26, (short)name.length);
                offset = archive.getFilePointer();
                archive.write(entryHeader.array());
                archive.write(name);
                catalog.add(this);
                crcAcc.reset();
                totalCompressed = 0;
                def.reset();
             * Finish writing entry data. Save the lenghts & crc for catalog
             * and go back and fill them in in the entry header.
            public void close() throws IOException {
                def.finish();
                while(!def.finished())
                    deflate();
                entryLater.position(0);
                crc = crcAcc.getValue();
                compressedSize = totalCompressed;
                uncompressedSize = def.getTotalIn();
                entryLater.putInt((int)crc);
                entryLater.putInt(compressedSize);
                entryLater.putInt(uncompressedSize);
                long eof = archive.getFilePointer();
                archive.seek(offset + 14);
                archive.write(entryLater.array());
                archive.seek(eof);
             * Write the catalog data relevant to this entry. Buffer is
             * preloaded with fixed data.
             * @param buf Buffer to organise fixed lenght part of header
            public void writeCatalog(ByteBuffer buf) throws IOException {
                buf.position(12);
                putDate(buf);
                buf.putInt((int)crc);
                buf.putInt(compressedSize);
                buf.putInt(uncompressedSize);
                buf.putShort((short)name.length);
                buf.putShort((short)0);  // extra field length
                buf.putShort((short)0);  // file comment length
                buf.putShort(DISC_NUMBER);  // disk number
                buf.putShort((short)0); // internal attributes
                buf.putInt(0);      // external file attributes
                buf.putInt((int)offset); // file position
                archive.write(buf.array());
                archive.write(name);
             * This writes the entries date in MSDOS format.
             * @param buf Where to write it
             * @TODO Get this generating sane dates
            public void putDate(ByteBuffer buf) {
                long msTime = (date.getTime() - MSEPOCH) / 1000;
                buf.putShort((short)(msTime % SECONDS_TO_DAYS));
                buf.putShort((short)(msTime / SECONDS_TO_DAYS));
        private Entry entryInProgress = null; // entry currently being written
        private java.util.ArrayList catalog = new java.util.ArrayList(12);  // all entries
         * Start a new output file.
         * @param name The name to store as
         * @param date Date - null indicates current time
        public java.io.OutputStream openEntry(String name, java.util.Date date) throws IOException{
            if(entryInProgress != null)
                entryInProgress.close();
            entryInProgress = new Entry(name, date);
            return this;
         * Creates a new instance of ZipOutputFile
         * @param fd The file to write to
        public ZipOutputFile(java.io.File fd) throws IOException {
            this(new java.io.RandomAccessFile(fd, "rw"));
         * Create new instance of ZipOutputFile from RandomAccessFile
         * @param archive RandomAccessFile
        public ZipOutputFile(java.io.RandomAccessFile archive) {
            this.archive = archive;
            entryHeader.order(java.nio.ByteOrder.LITTLE_ENDIAN);  // create fixed fields of header
            entryLater.order(java.nio.ByteOrder.LITTLE_ENDIAN);
            entryHeader.putInt(ENTRY_HEADER_MAGIC);
            entryHeader.putShort(MIN_VERSION);
            entryHeader.putShort((short)0);  // general purpose flag
            entryHeader.putShort(DEFLATE_METHOD);
            java.util.Calendar cal = java.util.Calendar.getInstance();
            cal.clear();
            cal.set(java.util.Calendar.YEAR, 1950);
            cal.set(java.util.Calendar.DAY_OF_MONTH, 1);
    //        def.setStrategy(Deflater.HUFFMAN_ONLY);
            MSEPOCH = cal.getTimeInMillis();
         * Writes the master catalogue and postamble and closes the archive file.
        public void close() throws IOException{
            if(entryInProgress != null)
                entryInProgress.close();
            ByteBuffer catEntry = ByteBuffer.wrap(new byte[46]);
            catEntry.order(java.nio.ByteOrder.LITTLE_ENDIAN);
            catEntry.putInt(CATALOG_HEADER_MAGIC);
            catEntry.putShort(VERSION_CODE);
            catEntry.putShort(MIN_VERSION);
            catEntry.putShort((short)0);
            catEntry.putShort(DEFLATE_METHOD);
            long catStart = archive.getFilePointer();
            for(java.util.Iterator it = catalog.iterator(); it.hasNext();) {
                ((Entry)it.next()).writeCatalog(catEntry);
            catEntry.position(0);
            catEntry.putInt(CATALOG_END_MAGIC);
            catEntry.putShort(DISC_NUMBER);
            catEntry.putShort(DISC_NUMBER);
            catEntry.putShort((short)catalog.size());
            catEntry.putShort((short)catalog.size());
            catEntry.putInt((int)(archive.getFilePointer() - catStart));
            catEntry.putInt((int)catStart);
            catEntry.putShort((short)0);
            archive.write(catEntry.array(), 0, catEntry.position());
            archive.setLength(archive.getFilePointer());  // truncate if old file
            archive.close();
            def.end();
         * Closes entry in progress.
        public void flush() throws IOException{
            if(entryInProgress == null)
                throw new IllegalStateException("Must call openEntry before writing");
            entryInProgress.close();
            entryInProgress = null;
         * Standard write routine. Defined by {@link java.io.OutputStream}.
         * Can only be used once openEntry has defined the file.
         * @param b  Bytes to write
        public void write(byte[] b) throws IOException{
            if(entryInProgress == null)
                throw new IllegalStateException("Must call openEntry before writing");
            crcAcc.update(b);
            def.setInput(b);
            while(!def.needsInput())
                deflate();
         * Standard write routine. Defined by {@link java.io.OutputStream}.
         * Can only be used once openEntry has defined the file.
         * @param b  Bytes to write
        public void write(int b) throws IOException{
            oneByte[0] = (byte)b;
            crcAcc.update(b);
            write(oneByte, 0, 1);
         *  Standard write routine. Defined by {@link java.io.OutputStream}.
         * Can only be used once openEntry has defined the file.
         * @param b  Bytes to write
         * @param off Start offset
         * @param len Byte count
        public void write(byte[] b, int off, int len) throws IOException{
            if(entryInProgress == null)
                throw new IllegalStateException("Must call openEntry before writing");
            crcAcc.update(b, off, len);
            def.setInput(b, off, len);
            while(!def.needsInput())
                deflate();
        * Gets a buffer full of coded data from the deflater and writes it to archive.
        private void deflate() throws IOException {
            int len = def.deflate(deflateBuf);
            totalCompressed += len;
            if(len > 0)
                archive.write(deflateBuf, 0, len);

  • .ZIP files and the ZipFile object

    Dove into java.util.zip this weekend and was most unhappy with the docs. Fortunately, searching these forums I was able to make some progress, but am still confused about the ZipFile class.
    I was able to open a FileInputStream, hand it to a ZipInputStream and read a .ZIP file. I was not able to read the .ZIP opening it as a ZipFile (I got the ZipEntries and the header info, but couldn't unzip the data).
    I was able to write a .ZIP with the reverse but was concerned that the ZipFile isn't even documented as supporting file writing. Is the ZipFile a useful thing in some way I haven't discovered, or should I just forget about it?

    this is a simple test for copying a zip file
    java ZipDemo c:\myZip.zip d:\testdir
    import java.util.zip.*;
    import java.io.*;
    import java.util.*;
    class ZipDemo
         public static void main(String [] arg) throws Exception
              ZipFile src = new ZipFile(arg[0]);
              File tgt = new File(arg[1]);     
              if(!tgt.isDirectory())
                   System.out.println(tgt+" is not found, or not a directory");
              for(Enumeration e = src.entries(); e.hasMoreElements(); )
                   ZipEntry ze = (ZipEntry) e.nextElement();
                   File target = new File(tgt, ze.getName());
                   try {
                        target.getParentFile().mkdirs();
                   }catch(NullPointerException npe){} // ignore case where file has no parent
                   if(!ze.isDirectory())
                        copy(src.getInputStream(ze), target);
         static byte [] buffer = new byte [16384];
         public static void copy(InputStream in, File target) throws IOException
              FileOutputStream out = new FileOutputStream(target);
              int bytesRead;
              while((bytesRead=in.read(buffer))>0)
                   out.write(buffer,0,bytesRead);
              out.close();
              in.close();     
    }

  • Why is my Zip file being created with size of O KB?

    I have the following code
    public static int createZip (String directory)
                       throws IOException {
         File path = new File( directory );
         File outZip = new File("c:\\wip\\sams9dbExport.zip");
         boolean boo = outZip.createNewFile();
         FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.endsWith(".xml");
        if ( outZip.exists() ) System.out.println("File exists");
         System.out.println(" Files and filters made");
         // These are the files to include in the ZIP file
         String[] fileList = path.list(filter);
        // Create a buffer for reading the files
        byte[] buf = new byte[1024];
        try {
            // Create the ZIP file
            String outFilename = "sams9dbExport.zip";
            ZipOutputStream out = new ZipOutputStream( new FileOutputStream( outFilename ) );
            // Compress the files
            for ( int i=0; i < fileList.length; i++ ) {
                FileInputStream in = new FileInputStream( "c:\\wip\\"+fileList[i] );
                 System.out.println( fileList[i] );
                // Add ZIP entry to output stream.
                out.putNextEntry( new ZipEntry( "c:\\wip\\"+fileList[i] ) );
                System.out.println("Added an entry");
                // Transfer bytes from the file to the ZIP file
                int len;
                while ( ( len = in.read( buf ) ) > 0 ) {
                    out.write( buf, 0, len );
                // Complete the entry
                out.closeEntry();
                in.close();
            // Complete the ZIP file
             out.close();
        } catch (IOException e) {
             System.out.println( e.toString() );
             return 0;
        return 1;
    }And I get the following output
    SQL> @ziptest
    File exists
    Files and filters made
    AH_QUERY.xml
    Added an entry
    myclob.xml
    Added an entry
    myclob1.xml
    Added an entry
    myclob2.xml
    Added an entry
    PERSONNEL.xml
    Added an entry
    PERS_ALG.xml
    Added an entry
    sampledoc.xml
    Added an entry
    ut_ah_query1.xml
    Added an entry
    ut_provider.xml
    Added an entry
    PL/SQL procedure successfully completed.
    SQL>
    But my file is created empty. I previously added a println statement in the while loop to see if it was reading and writing bytes and it was.
    Any ideas?

    I have the following code
    public static int createZip (String directory)
    throws IOException {
    File path = new File( directory );
    File outZip = new
    = new File("c:\\wip\\sams9dbExport.zip");
    boolean boo = outZip.createNewFile();So these two lines will create sams9dbExport.zip with size 0 bytes, if file didn't exist.
    No need to do that....
    try {
    // Create the ZIP file
    String outFilename = "sams9dbExport.zip";
    ZipOutputStream out = new ZipOutputStream(
    tStream( new FileOutputStream( outFilename ) );Probably you are looking a wrong "sams9dbExport.zip" -file. Your application will create two "sams9dbExport.zip"-files, one into wip-folder with 0 bytes, and other into default directory.
    >
    But my file is created empty. I previously added a
    println statement in the while loop to see if it was
    reading and writing bytes and it was.
    Any ideas?

  • What is the max size of a zip file with the JDK1.5 ?

    Hello everybody,
    I'm a french student and for a project, I need to create a zip file, but I don't know in advance the number and the size of files to include in my zip.
    I wish to know if someone have the answer to my question : what is the max size of a zip file with the JDK1.5 ? I believe that with the JDK1.3, the limit size of a zip was about 2Go, wasn't ?
    Thank you for all answer !
    Good day !
    PS : sorry for my very poor english ;-)

    Here is all I have found for the moment :
    ...Okay, what about my suggestion of creating your own 10GB file?
    Try this:import java.io.File;
    import java.io.RandomAccessFile;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    import java.util.Random;
    class Main {
        public static void main(String[] args) {
            long start = System.currentTimeMillis();
            int mbs = 1024;
            writeFile("E:/Temp/data/1GB.dat", mbs);
            long end = System.currentTimeMillis();
            System.out.println("Done writing "+mbs+" MB's to disk in "+
                    ((end-start)/1000)+" seconds.");
        private static void writeFile(String fileName, int numMegaBytes) {
            try {
                int numBytes = numMegaBytes*1024*1024;
                File file = new File(fileName);
                FileChannel rwChannel =
                        new RandomAccessFile(file, "rw").getChannel();
                ByteBuffer buffer = rwChannel.map(
                        FileChannel.MapMode.READ_WRITE, 0, numBytes);
                Random rand = new Random();
                for(int i = 1; i <= numMegaBytes; i++) {
                    for(int j = 1; j <= 1024; j++) {
                        byte[] bytes = new byte[1024];
                        rand.nextBytes(bytes);
                        buffer.put(bytes);
                rwChannel.close();
            } catch(Exception e) {
                e.printStackTrace();
    }On my machine it took me 43 seconds to create a 1GB file, so it shouldn't take too long to create your own 10GB. Then try zipping that file.
    Good luck.

  • Cannot see zipped files in Windows Explorer

    I used the code below to create a zip file. When I use Winzip to open a zip file named test.zip, I can see all the files (a.txt, b.class, etc.) that have been zipped. But, when I double-click on the test.zip in Windows Explorer (Windows XP Professional), I cannot see any of the zipped files.
    Can someone give me some pointers?
    import java.util.*;
    import java.util.zip.*;
    import java.io.*;
    public class CreateZip
         public CreateZip()
         public void createZipFile(String[] all_array, String zipfilename)
              FileOutputStream pout; // declare a file output object
    PrintStream p;
              String file_path = "D:\\Docs\\FedPlanner\\";
    try
    pout = new FileOutputStream(file_path + "FedPlanner_Zip_log.txt");
    p = new PrintStream( pout );
                   for (int i = 0; i < all_array.length; i++)
                        System.out.println("all_array = " + all_array);
                        p.println (all_array[i]);
    p.close();
    catch (Exception e)
    System.err.println ("Error writing to file");
              byte[] buf = new byte[1024];
              try
                   String outFilename = file_path + zipfilename;
              ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
                   for (int i=0; i< all_array.length; i++) //
                   FileInputStream in = new FileInputStream(file_path + all_array[i]);//filenames
                   out.putNextEntry(new ZipEntry(file_path +all_array[i]));//filenames
                   int len;
                   while ((len = in.read(buf)) > 0)
                   out.write(buf, 0, len);
                   out.closeEntry();
                   in.close();          
              out.close();
              catch (IOException e)
                   e.printStackTrace();
         public static void main(String args[])
              for(int i=0; i < all_array.length; i++)
                   System.out.println("x = " + all_array[i]);
              CreateZip create = new CreateZip();
              create.createZipFile(all_array);

    I have never created a zip file using Java . But from what i know about Winzip and Window Explorer, here's my takes on it:
    1. Winzip works with severals different compression algorithm 9including their own)
    2. Winzip has the ability to display the content of the zip file (if the zip file happens to be one of the compression algorithm they supported....otherwise, it's highly unlikely, winzip can even open the file)
    3. Window Explorer does not call Winzip to display the content of Winzip file. rather, Window Explorer has its own utility to look into the Winzip for files and display them. Note: they probably only do this for the popular compression algorith (such as Winzip .zip, probably .tar...but highly doubtful of the one that Java use to make a zip file).
    So..it's probably Window Explorer does not supports display that compression algorithm (the one Java use) for a Winzip file.
    Example...you created a new format for an image call .mypics
    Window Explorer can display a thumb nail for .bmp, .jpeg, and quite a few other
    You created an application to display the image. Now..in Window Explorer, when you click on the icon, the thumbnail of the pic is not display...this is because Window Explorer does not have a util to do thumbnail for that format.

  • Download report as compressed/zip file

    Hi,
    i was wondering if it is possible to download a report compresed/(zip file). Some reports are more then 10MB and it's sometimes timeconsuming to download it to you local machine via a slow internet connection. If this is possible.. Is it then also possible to create an Ibot to sent a zipped report to mail :)
    regards,
    Osman

    I don't think you can compress a file or zip it and then download it. But you can schedule an ibot to download the file to a local drive using javascripts at night when no one is around and it doesn't matter how long it takes. Then, if you need to email them out, you can zip them there and email them. Here are some links that will help you with the javascripting:
    http://oraclebizint.wordpress.com/2007/12/17/oracle-bi-ee-101332-calling-java-scripts-and-java-classes-from-ibots/
    http://sureshotstrategies.wordpress.com/2008/04/12/writing-ibots-results-to-a-file/

  • ZipException creating zip file

    I am trying to modify a zip file, by creating a new zip file and copying the entries over selectively. I use the following code:
    try
                   zipFile = new ZipFile(args[0]);
                   zos = new ZipOutputStream(new FileOutputStream(args[1]));
                   entries = zipFile.entries();
                   while(entries.hasMoreElements())
                        entry = (ZipEntry)entries.nextElement();
                        if (entry.getName().endsWith(".class") || entry.isDirectory() ||
                                  entry.getName().endsWith(".MF"))
                             zos.putNextEntry(entry);
                   zipFile.close();
                   zos.close();
              catch (IOException ioe)
                   System.err.println("Unhandled exception:");
                   ioe.printStackTrace();
                   System.err.println(entry);
                   return;
    However it throws an exception for the second entry that it encounters:
    invalid entry size (expected 10804 but got 0 bytes)
         at java.util.zip.ZipOutputStream.closeEntry(Unknown Source)
         at java.util.zip.ZipOutputStream.putNextEntry(Unknown Source)
         at delPNGsFromJar.main(delPNGsFromJar.java:34)
    It doesn't matter which entry it is, it always fails on the seconds.
    Anyone have any ideas?

    A ZipEntry only contains data associated with the entry, it does not contain any actual data. In addition to putting an entry with "putNextEntry" you have to write its data.
    You do this by getting the entry's InputStream from the ZipFile object, and writing what you read from it to the ZipOutputStream. Don't forget to close the entry when you're done.

Maybe you are looking for

  • Schedule DO NOT DISTURB differently on certain days.

    I go to college and DO NOT DISTURB is a god send as I can schedule it to work during class time.  However, I do not attend class EVERY day and my schedule varies day to day. Is there a way (or a way in the works (HINT HINT APPLE)) of being able to sc

  • Will I need to install OS X Lion?

    Hello, Im currently running Snow Leopard and I wish to get the Moutian Lion OS when it comes out. So Im wondering that do I need to install Lion first or can I go straight ahead and install Moutiain Lion.

  • How can I make text fill a custom shape?

    I am trying to make text in the shape of a fish, kinda like this: Can someone help me out with this one?!?!  Thanks!

  • How to remove the list of on-line ids that appear when logging on

    I have several people logging on to my computer. Every time I begin my id, a list of all the ids that have been used appears. I want to delete that list and in fact prevent any such list from being kept,

  • Subscribe and Notification via email

    We would like to use to subscribe mechanism in Oracle Portal. Instead of displaying the new items in a portlet, we wish to notifiy daily via email. Has somebody done something similar and can provide the source code? regards, André