Read zip files created by ZipOutputStream

Hello :)
I am wondering if it is possible to create a zipfile using ZipOutputStream, which can be read using ZipInputStream with out using the ZipFile work-around discussed in http://forum.java.sun.com/thread.jspa?forumID=256&threadID=492219. This is no option for me, because we have a lot of client applications deployed, which cannot easily be altered.
Are there any (third-party) libraries which I can use?
-M1chael

try it
// These are the files to include in the ZIP file
String[] source = new String[]{"source1", "source2"};
// Create a buffer for reading the files
byte[] buf = new byte[1024];
try {
// Create the ZIP file
String target = "target.zip";
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(target));
// Compress the files
for (int i=0; i<source.length; i++) {
FileInputStream in = new FileInputStream(source);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(source[i]));
// 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) {

Similar Messages

  • Zipped files created with Java won't unzip with Java

    Hello there,
    I have written a class for unzipping a zip file using the 'ZipFile' class. It works perfectly fine when I extract zip files that have been created with XP, Winzip, or Winrar.
    I am now experimenting with creating zip files using the ZipOutputStream (http://forum.java.sun.com/thread.jspa?forumID=256&threadID=366550 by author smeee). The code works great for creating the zip file, but when I try and unzip it with the zipfile class mentioned above it throws an exception.
    The error that the following code gives me when it tries to convert an element from the enumeration to a ZipEntry is this: java.io.FileNotFoundException: C:\testfiles\out\high\BAUMAN\00001.jpg (The system cannot find the path specified)
    NOTE: The file is there by the way!!! :-)
    See the code for extracting here:
    try {
                 zippy = new ZipFile(fileName);
                 Enumeration all = zippy.entries();
                 while (all.hasMoreElements()) {//loop through all zip entries
                              getFile((ZipEntry)all.nextElement()); <<<=====FAILS HERE
    } catch (IOException err) {
                 System.err.println(err.toString());
                 return;
    }Now if I extract the zip file with winzip, then rezip it with winzip and run the above method again it works with no errors. Any thoughts. Any help would be greatly appreciated.
    Jared

    Hello All,
    For anyone else who use the forum posting by smeee as a guide to create a zipper (http://forum.java.sun.com/thread.jspa?forumID=256&threadID=366550 by author smeee).
    I was tracing through the code and found that there is a statement that adds 1 character (strSource.length()+1) to the source path. This was causing the following bug:
    In windows it was placing objects like this \myfolder\myfile.txt
    In unix it was placing objects like this yfolder\myfile.txt
    Naturally a path like \myfolder... in the zip index was causing problems. I have added a case statement that tests the OS and then adds two chars if windows to compensate for the 'C:' and does nothing if Unix. The code now runs perfectly on either OS.
    Thanks for your response guys!
    Jared

  • Error reading zip file in Java 6

    We have a bespoke installer program that fails, intermittently, in Java 6 on Windows. After installing some files, it then fails with a stack trace like this:
    java.util.zip.ZipException: error reading zip file
         at java.util.zip.ZipFile.read(Native Method)
         at java.util.zip.ZipFile.access$1200(ZipFile.java:29)
         at java.util.zip.ZipFile$ZipFileInputStream.read(ZipFile.java:447)
         at java.util.zip.ZipFile$1.fill(ZipFile.java:230)
         at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:141)
         at java.io.FilterInputStream.read(FilterInputStream.java:90)
         at com.XXXX.trent.installer.Installer.writeStreamToFile(Unknown Source)
         at com.XXXX.trent.installer.Installer.installFile(Unknown Source)
         at com.XXXX.trent.installer.PatchFileInstaller.installFile(Unknown Source)
         at com.XXXX.trent.installer.PatchFileInstaller.installFiles(Unknown Source)
         at com.XXXX.trent.installer.UpgradeInstaller$TpfAction.run(Unknown Source)
         at com.XXXX.trent.installer.UpgradeInstaller.runActions(Unknown Source)
         at com.XXXX.trent.installer.UpgradeInstaller.install(Unknown Source)
         at com.XXXX.trent.installer.TrentInstall$SoftwareInstallStage.install(Unknown Source)
         at com.XXXX.trent.installer.TrentInstall$UpgradeInstallWorker.install(Unknown Source)
         at com.XXXX.trent.installer.PatchInstall$InstallWorker.construct(Unknown Source)
         at com.XXXX.trent.utils.SwingWorker$2.run(Unknown Source)
         at java.lang.Thread.run(Thread.java:619)The same code works in Java 5 on the same environments that it now fails in Java 6 (1.6.0_16).
    Any ideas?
    Thanks.

    gimbal2 wrote:
    it is not weird, it is a bug in the application. Don't let the upgrade from Java 5 to Java 6 make you believe otherwise.It's a singularly bad exception message though. I would have thought that something from java.util might be a bit more explicit about what the problem is.
    Winston

  • Program to read zip files???

    im looking for a program to read zip files?Is this even possible on a mac? Im running 10.4.11 on my ibook g4

    Hello,
    What you need is a program that can OPEN .zip files. Go here: http://my.smithmicro.com/mac/stuffitexpander/index.html
    Download the free installation and just follow the instructions to open .zip files.
    Carolyn

  • Error reading zip file containing an excel file

    Hi all,
    Using servlets I am able to zip an excel file using java.util.zip package. The excel file is created using POI API.
    While I save and extract the zip file on my machine and then open the file in MS Excel. Excel pops a message saying "MS Office Excel has encountered a problem and need to close" and it gives me an option to "Recover my work and restart MS Office Excel". I select the option and then MS Excel does a document recovery and I am able to view my data. I get an excel repair log file saying as follows
    "Microsoft Office Excel File Repair Log
    Errors were detected in file 'C:\Documents and Settings\JohnDoe\Desktop\excel\test.xls'
    The following is a list of repairs:
    Damage to the file was so extensive that repairs were not possible. Excel attempted to recover your formulas and values, but some data may have been lost or corrupted.
    I have attached my servlet code down below I suspect there is a problem with PrintWriter to output or do I need to use OutputStream to write excel data.
    Below is my servlet code:
    import java.io.*;
    import javax.servlet.*;
    import org.apache.log4j.Logger;
    import java.util.*;
    import java.util.zip.*;
    import java.net.*;
    import org.apache.poi.hssf.usermodel.*;
    import org.apache.poi.hssf.record.*;
    import org.apache.poi.hssf.util.*;
    public class ZipServlet extends HttpServlet {
         * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
         * javax.servlet.http.HttpServletResponse)
         public void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
              makeZip(request, response, "GET");
         * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
         protected void doPost(HttpServletRequest request, HttpServletResponse response)
                   throws ServletException, IOException {
                   makeZip(request, response, "POST");
         public void makeZip(HttpServletRequest request, HttpServletResponse response, String methodGetPost) {
              Logger logger = Logger.getLogger(ZipServlet.class);
              try
                   int id=1;
                   ServletContext sc = getServletContext();
         HttpSession session = request.getSession();          
                   ConnectionPoolManager cpm = (ConnectionPoolManager)sc.getAttribute("CONNECTION_POOL_MANAGER");
                   ConnectionPool cp = cpm.getConnectionPool(id);
              createTestExcelZip(request,response,methodGetPost,session);
              } catch (Exception e2) {
         public void createTestExcelZip(HttpServletRequest request, HttpServletResponse response,
                   String methodGetPost,HttpSession session
                   )throws ServletException, IOException
              Logger logger = Logger.getLogger(ZipServlet.class);
              try
              {      //Create an Excel Workbook and placing value "Test" in the first cell
                   HSSFWorkbook wb = new HSSFWorkbook();
                   HSSFSheet sheet = wb.createSheet("new sheet");
                   HSSFCell cell=null;
                   HSSFRow row = sheet.createRow((short) 0);
                   short column = 0;
                   cell = row.createCell(column);
                   cell.setCellValue(new HSSFRichTextString("Test"));
                   HSSFCellStyle fontStyle = wb.createCellStyle();
              HSSFFont f = wb.createFont();
              f.setFontHeight((short) 200);
              f.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
              fontStyle.setFont(f);
              cell.setCellStyle(fontStyle);
              response.setContentType("application/zip");
                   response.setHeader("Content-Disposition","attachment; filename=zipExcelRecordFiles.zip;");
                   int BUFFER = 2048;
                   byte buf[]=new byte[300000];
                   ByteArrayOutputStream baos = new ByteArrayOutputStream();
                   ZipOutputStream zos = new ZipOutputStream( baos );
                   ByteArrayInputStream is = null;
                   BufferedInputStream origin = null;
                   byte[] b = null;
                   String fileName = null;
                   b = wb.getBytes();
                   fileName = "testExcelRecords.xls";
                   try
                   is = new ByteArrayInputStream(b);
                   origin = new BufferedInputStream(is, BUFFER);
                   zos.putNextEntry(new ZipEntry(fileName)); // Add ZIP entry to output stream.
              int count;
              while((count = origin.read(buf, 0, BUFFER)) != -1)
              zos.write(buf, 0, count);
              zos.closeEntry(); // Complete the entry
                   is.close();
                   }catch(Exception e)
                        logger.error(e);
                   zos.close();
              PrintWriter pr = response.getWriter();
                   pr.write(baos.toString("ISO-8859-1"));
                   pr.close();
              catch(Exception e)
              logger.error(e);     
         * @see javax.servlet.GenericServlet#destroy()
         public void destroy() {
    Any help would be appreciated.
    Regards
    jdcunha

    Jdcunha,
    I am new to the field but encountered the same problem and recently found a solution. Hope this helps.
    For my project I wanted to create individual Excel 2003 workbooks for each file I created. Excel would give me the same error it gave you when I used the same HSSFWorkbook object. I tried creating a new Workbook object each time, but ran into the same issue.
    I ended up fixing the error by creating a new instance of my write-to-excel class each time I wanted to create a new workbook, instead of just recreating a new HSSFWorkbook object. It works perfectly and the Excel errors don't show. It may also be important to note I used OutputStream, I did not try it with printwriter.

  • File created from ZipOutputStream not opening as Windows Compressed Folder

    I create a file using java.util.ZipOutputStream using JDK 5. I can open the file in WinZip. But when I try to open as "Compress (zipped) Folders" in Windows XP, I just get an empty folder. Is there something I have to do other than creating a ZipEntry for each file? From WinZip, I can look at the files and extract them and everything seems to be fine including the folder structure.
    Thanks.

    Make sure there are no invalid characters in folders or files stored in the zip file.
    Windows does not allow the following characters in folder and file names.
    \ / : * ? " < >
    Check your zip folder structure to see if it contains any of these characters.

  • File Adapter to read Zip file and send it as input to another webservice

    Hi,
    I have the below requirement:
    1. A service will generate 3 attachments and place it in a particular directory.
    2. SOA service has to pick those 3 files and send those files as input to another custom application which will email.
    Design :
    1. First SOA will create an archive file of those 3 attachements and then file adapter will poll for that zip file in that location and send that file as a whole to the custom application.
    Query:
    Now my question, is the above design feasible? If so, how to configure the file adapter to pass the file as input to that custom application?
    Kindly do the needful
    Thanks,
    Priya

    You can accomplish this via java embedding activity...Create a java embedding, which will create a zip file.. this java code is easy to implement..
    You can also do away with un-necessary polling file adapter.. and you can use "Synchronous File Read" operation of File Adapter.. For Sync Read, you'll have to pass the zip file name, which you can easily fetch from java embedding activity..
    Let me know, if this doesn't work.

  • Reading .ZIP files using File Adapter

    Hi,
    I am using BPEL File Adapter to read files. The files to be read are XML files which are in zipped format.
    so how should I read these .zip files and extract the XML files from that.
    Thanks
    /Kiran.

    If the xml files are all in the same directory (not in any directory structure relative to the parent directory), you can do something like this.
    - create a bpel process to read the zip files as it comes into the directory]
    - Have a file adapter inbound for the receive
    - Call windows .bat command within the bpel process to run an unzip command on that directory
    - Have another bpel process that reads *.xml files and this will get kicked off.
    There are so many ways of solving this: like having a cron job to unzip the files coming in etc. But, if you have a directory structure for these XML files and if the structure is dynamic, it is difficult to configure the file adapter for that.

  • Reading ZIP files

    Is it possible to read content of ZIP files.
    Iam using ORACLE forms 6i.
    In our company, we are creating a zip file with two folder src and lib, where SRC contains FMB files abd LIB contains PLLfiles.Now i want to know whether instead of us seeing the contents, is it possible to check whether fmx and plx are present in correspoding folder using some api methods.
    If u can find any please tell me .. it will be of great use

    I dont about the api's, but one way cud be unzipping the files in temp folder thru winzip command line and then checking the files existence.

  • ZIP file created in OS X won't open correctly in XP

    Hi there,
    I created a ZIP file of a 196MB folder (full of pictures) in OS X using the right-click, "Compress." When a friend tried to unzip this file in Windows XP, the only file inside the archive was a 0KB file titled _MACOSX. The ZIP file itself was still the correct size, but it was essentially 196MB of empty space. When I open the same ZIP file on my Mac, everything appears as it should,
    Any thoughts/ideas? Thanks, in advance, for your help.

    You're right - my friend was trying with the built-in XP ZIP support.
    I'll have him try one of those programs. Thanks.

  • Help:  unable to open files created with ZipOutputStream

    I am seeing some weird behavior with ZipOutputStream, using JDK 1.3.1_01 on Win2K. The code that follows is a snippet from a servlet that delivers a ZIP archive of a set an entire directory tree. I was preparing to roll it into production, but one of my testers noticed a bug that I didn't see.
    It seems that her version of WinZip (6.x) was unable to properly extract the files from the archive while mine (8.0) had no problems. I then tried a couple of other programs, and I've been able to reproduce the behavior with the built-in viewer in Lotus Notes 5 (the only other utility I had handy).
    I've made sure to call closeEntry() on each ZipEntry, and to call finish() before close() on the ZipOutputStream itself. Has anyone seen this behavior besides me?
    Thanks and regards,
    Casey
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition","attachment; filename=\"package.zip\"");
        File dir = new File(m_templateDir);
        ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
        addFilesToPackage(dir, "", out);
        out.finish();
        out.close();
    // Recursively walks the directory, adds files to the output stream,
    // and calls itself to handle sub-directories
    private void addFilesToPackage(File dir, String pathPrefix, ZipOutputStream out)
    throws IOException {
        File[] list = dir.listFiles();
        for (int k=0; k<list.length; k++) {
            File f = list[k];
            if (f.isDirectory()) {
                addFilesToPackage(f, pathPrefix + f.getName() + "/", out);
            } else {
                ZipEntry ze = new ZipEntry(pathPrefix + f.getName());
                out.putNextEntry(ze);
                InputStream in new FileInputStream(f);
                byte[] buff = new byte[2056];
                int bytesRead = 0;
                while((bytesRead = in.read(buff)) > -1) {
                    out.write(buff, 0, bytesRead);
                out.closeEntry();
                in.close();
    }

    I had also a problem with W2K when using ZipInputStream, I could not to solve it.
    so I used Unpacked Streams.
    weird indeed.
    Sometimes it works just fine.
    FileInputStream fis;
    byte [] in;
    //ZipFile zf = new ZipFile(new File("data/products.zip"));
    //ZipEntry ze = zf.getEntry("products.wsl");
    //fis =new BufferedInputStream( zf.getInputStrea(ze));
    fis = new FileInputStream("data/products.wsl");
    koko = fis.available();
    in = new byte[koko];
    fis.read(in);
    fis.close();
    I think code was something like abowe (there has been a while...)

  • Zip file created in Snow Leopard can't be opened on a PC

    Hi,
    I've created a zip file of a folder containing Word and pdf files using File>Compress in Snow Leopard.
    After emailing to clients, they cannot open the zip file on their PCs.
    Any help? I thought zip was supposed to be universal.
    Thanks in advance!

    All clients, or some clients? How big are the zip files?
    Usually when this happens, one of two things is going on: one of your mail servers is truncating the message (cutting off part of the attachment) because the message exceeds some pre-determined maximum message size (or the mailbox goes over a quota), OR one of you is running a virus/malware scanner on your mail server that objects to certain file types (it's not uncommon to strip .ZIP, .COM, and .EXE files).
    There's also the possibility that a Windows client just doesn't understand the file's type. While that shouldn't be, it does happen sometimes (I've seen it with Lotus Notes, for example). In that case, the recipient should save the attachment as a file on their desktop and open it from the desktop.

  • Zip file created on OS X fails to open in Windows

    I have created a 10 GB zip file (I suppose that it is a zip 64 file) as a backup of my Mac. I have moved it into a Windows computer, however, whatever program I use, it fails to open. The closest I got was using a 3rd party zip program, which succeeded in reading the directories, but not the individual files. Is there a program that I can use, or is this only compressible on a Mac (on a Mac, I have succeeded in uncompressing the file)?

    There are of course several different companies that make and furnish there product on the market many are free while others you have to pay for. In all the years I have been playing with computers I have found this one to be one of the best on the market.
    http://mac.winzip.com/features.htm
    Scroll down and you will find the capabilities. You can create and open either Mac or PC.
    They also offer a trial version so you can see if this is what you want.
    Cheers
    Don

  • Read Zip File

    Hi,
    I have one zip file and want to read it file by file can you please tell me how can I achieve this???
    OR
    Can anyone please tell me about how can I get absolute path of the file which is resided in the zip file
    For example,
    if I have an zip file Test.zip which contains 4 zip files t1.xml,t2.xml.... and so on and resided on my local drive (D:).
    So, is there any way where I can get absolute path of these files like "D:\\Test.zip\\t1.xml","D:\\Test.zip\\t2.xml"
    Thanks in advance!!!

    rpdesh wrote:
    You can read the contents of the Zip file by creating ZipInputStream object.
    The constructor takes the file path and using the method getNextEntry() you will get the ZipEntry present in the zip file.
    Something like this...
    File file = new File("Zip file path here");
    ZipInputStream zip = new ZipInputStream( new FileInputStream( file ))
    ZipEntry zipEntry = null;
    while( zip.getNextEntry() != null )
    zipEntry = zip.getNextEntry();
    // Other operaions here
    <shakes-head/>
    That code is skipping over every other ZipEntry. Try this:
    for(ZipEntry zipEntry; (zipEntry= zip.getNextEntry()) != null;) {
         System.out.println(zipEntry.getName());
    }One could also use java.util.zip.ZipFile.

  • How to read zip files?

    Hi,
    I am trying to read data from zip files. can anyone say what i did wrong in this configuration?
    <?xml version="1.0" encoding="UTF-8"?>
    <Graph author="123" created="Mon Oct 08 10:06:08 IST 2012" guiVersion="3.2.1" licenseCode="CloverETL Designer single license" licenseType="CloverETL Designer single license" modified="Mon Oct 08 10:06:08 IST 2012" modifiedBy="123" name="Default graph name" revision="1.0" showComponentDetails="false">
    <Global>
    <Dictionary/>
    </Global>
    <Phase number="0">
    <Node enabled="enabled" fileURL="zip:(${DATAIN_DIR}/Archive1.7z)" guiHeight="93" guiName="UniversalDataReader" guiWidth="148" guiX="230" guiY="116" id="DATA_READER1" type="DATA_READER"/>
    <Node enabled="enabled" guiHeight="67" guiName="Trash" guiWidth="128" guiX="670" guiY="157" id="TRASH0" type="TRASH"/>
    <Edge debugMode="true" fromNode="DATA_READER1:0" guiBendpoints="632:312|632:175" guiLocks="572|null|null" guiRouter="Manual" id="Edge0" inPort="Port 0 (in)" metadata="Metadata1" outPort="Port 0 (output)" toNode="TRASH0:0"/>
    </Phase>
    </Graph>

    Based on your filename Archive1.7z you might have a 7z format 7zip file. I don't think this archive format is supported - you'll need to use a supported format such as ZIP.
    Best
    Brett

Maybe you are looking for

  • Ram compatibility for White Macbook 2006

    Want to upgrade RAM and note Apple specs say RAM Type: PC2-5300 SO-DIMM 200 pin Someone local to me is selling the following 2007 Two x 1 GB PC2-5300 S)-CIMM/CL5 laptop ram # Memory Type: DDR2 667 SDRAM (MicroDIMM) # Capacity: 1GB # Bus Speed: 667MHz

  • HT202297 The Reminders app on my OS X version 10.9 doesn't seem to have badge icons for apps that are overdue.  How do I get the badge icons for the app?

    Being overtly organised, I assign due times to all my reminders on the reminder app.  Recently, I realised that the badge icons (detailing the number of overdue reminders) do not pop up anymore.  How do I get them to reappear again?

  • The Error Trace

    Exception occurred during event dispatching: java.lang.NullPointerException at DataD$MyComboListener.actionPerformed(DataDictionary.java:143) at javax.swing.JComboBox.fireActionEvent(JComboBox.java:865) at javax.swing.JComboBox.selectedItemChanged(JC

  • How to reset mac admin password for os x 10.8.5

    cannot update software because i cannot remeber my computer password (admin) and i need to reset it. Please help.

  • Is iWeb for me?

    Hi, I've never had a homepage; never published photos or podcasts; never had a blog. But I'd quite like to get into blogging... Is iWeb suitable for me? I just want to blog; only friends will subscribe - but I want it to look professional... What do