Create a zip files in a special way

Dear all,
Following my yesterday's posting, I would clarify my questions:
I successfully created a zip file which contains a folder structure and two files from strings. See attached codes.
However, I don't like the way that I physically created subfolder and files before add them to the zip file.
Is there any possibility to avoid that part of creating multiple folders?
Regards.
Pengyou
package com.zip.test;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipTest {
     static final int BUFFER = 2048;
     public static void main(String argv[]) {
          try {
               BufferedInputStream origin = null;
               FileOutputStream dest = new FileOutputStream("mytest.zip");
               ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
                         dest));
               // out.setMethod(ZipOutputStream.DEFLATED);
               byte data[] = new byte[BUFFER];
               try {
                    String strManyDirectories = "root/dir1/dir2";
                    // Create multiple directories
                    boolean success = (new File(strManyDirectories)).mkdirs();
                    if (success) {
                         System.out.println("Directories: " + strManyDirectories
                                   + " created");
                    File outputFile = new File("root/dir1/dir2/test.html");
                    BufferedWriter bufferedWriter = new BufferedWriter(
                              new FileWriter(outputFile));
                    bufferedWriter.write("Hello, Test");
                    bufferedWriter.close();
                    File outputFile1 = new File("root/dir1/dir2/test1.html");
                    BufferedWriter bufferedWriter1 = new BufferedWriter(
                              new FileWriter(outputFile1));
                    bufferedWriter1.write("Hello, Test1");
                    bufferedWriter1.close();
               } catch (IOException e) {
               String files[] = { "root/dir1/dir2/test.html",
                         "root/dir1/dir2/test1.html" };
               for (int i = 0; i < files.length; i++) {
                    System.out.println("Adding: " + files);
                    FileInputStream fi = new FileInputStream(files[i]);
                    origin = new BufferedInputStream(fi, BUFFER);
                    ZipEntry entry = new ZipEntry(files[i]);
                    out.putNextEntry(entry);
                    int count;
                    while ((count = origin.read(data, 0, BUFFER)) != -1) {
                         out.write(data, 0, count);
                    origin.close();
               out.close();
          } catch (Exception e) {
               e.printStackTrace();

pengyou wrote:
But I did not understand how to convert a String to ZipOutputStream with a user choosen file name and a user choosen folder structure.
I am blocked at that point. Sorry for repeating the same question.
That doesn't make sense to me. Even more so as your sample code suggests that you are familiar with Writer and ZipEntry concepts. Can you explain in detail where you are stuck or what part of my previous suggestion was unclear to you?
Scratch that, I think I finally understand your problem. I think the following sample code will get you on track:import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;
import java.io.FileOutputStream;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
public class ZipTest {
    public static void main( String[] args ) throws Exception {
        final String[] content = {"bla", "blubber"};
        final String[] names = {"root/content1/c1.txt", "root/content2/c2.txt"};
        final String path = System.getProperty("user.home") + "/test.zip";
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(path));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));
        for (int i = 0; i < content.length; ++i) {
            final ZipEntry entry = new ZipEntry(names);
zos.putNextEntry(entry);
bw.write(content[i]);
bw.flush();
zos.closeEntry();
// this will close zos, too
bw.close();
Edited by: thomas.behr on Apr 22, 2009 4:10 PM

Similar Messages

  • Creating a zipped file from table data

    I am currently extracting data from a table and creating a flat file which is read later to create a compressed (zip) file.
    Is there a way that I can create a zipped file in one step (i.e. directly from the table data)? I am trying to reduce the number of file i/o hits in my appication.
    Thanks,
    Minesh

    Is there a way that I can create a zipped file in one step (i.e. directly from the table data)?Yes. Instead of doing something like:
    FileOutputStream fout = new FileOutputStream("flatfile");
    // write using foutdo this:
    ZipOutputStream zout = new ZipOutputStream("flatfile.zip");
    zout.putNextEntry(new ZipEntry("flatfile"));
    // write using zout

  • Problems creating/extracting ZIP files, anyone?

    Greetings,
    I am having some odd bugs with OSX in creating and extracting ZIP files.  I’m curious if anyone else has run across this or if anyone has any remedies to suggest.
    The issue is that when I extract a ZIP archive, the extracted files have their creation dates and modification dates changed from the original versions.  For example, I have a directory created in 2010 and all the files were created and last modified in 2010.  However, when I ZIP the directory and re-extract it, many of the file dates change.  Some files have the creation dates changed so to match the last modified date.  In other cases, both the creation date and modification date are changed to something later than both, perhaps the date the directory was ZIPed or the date the directory was extracted.  And some files don’t seem to have the dates changed. 
    I have tried various options, such as terminal, and third party programs (BetterZip, Keka, Stuffit, & Archiver to name a few) and they all seem to have some variation of this behavior.  I have tried creating the Zip with one program and extracting with the other, and still this behavior persists.  Different files seem to be affected with each combination of creating and extracting programs. 
    Another odd behavior was that I tried password protecting some directories with financial data, and OSX could create the ZIP file with the password, but OSX could not unzip the file with the password it created for some files.  In every case, third party program could unzip the files with the password created in the terminal command.  This seem to happen inconsistently. 
    I have tried creating a dummy account and tested it in that account, with similar results.
    I’ve read the man page for the command line version of ZIP to see if there is some -option to preserve dates, but found nothing.  The typical command looks like this:
    > zip -er filename.zip  sourceDir
    > unzip filename.zip
    File types include directories, PDFs, Text docs, Quicken files.  Ive tested other directories too with other file types.  It doesn’t seem to affect every file, but seems unpredictable.  Luckily, I still have the original uncompressed version of most directories.  But I really want to archive some directories and unarchive them when needed.  The dates matter to me because they are mostly financial files and I use the dates to know what versions were used for taxes and other things.  Also, if dates change, then backup programs start replacing the good backups with files with the corrupted dates. 
    I’d appreciate any suggestions or feedback.  I there some bug in the ZIP protocol?  Is there some bug in OSX file system that is corrupting the dates with the archive and unarchive process? 
    Thank you for any suggestions-
    OSX 10.9.5,
    MBPro 2012

    OK, sorry did not read it correctly.  Read the first sentance and quit.
    No, Bridge is just a browser.  You can extract more than one file at a time in Win. Explorer.  You have to do them individually, but can run multiple extractions at the same time.
    There are other zip/unzip programs out there.  I know the the CS6 beta a number of users could not open it with WinZip and used alternate product just fine.

  • How to create a zip file whith passwprd ?

    Hi Im trying to create a zip file using the java zip support, the zip file is being created correctly now I have one doubt I would like to know if the zip file can be protected with a password as Winzip does, if so could you tell me please how to do it.
    Regards,
    Antonio
    [email protected]

    With Core Java, for all I know you still can't.

  • Compressing a folder creates two zip files

    I've got a folder called Blanks/ABC FM/SMS/Other and when I compress it I get two zip files of the same size: one with the correct name and the other called Archive.zip. When I remove the space I only get the Archive.zip. When I remove the slashes I get the correct zip file only.
    Is this a bug that I should report? How?

    If you were expecting C/D to compress to C/D.zip instead of Archive.zip I think I have an explanation for that.
    The unix file system which is the underlying OSX file system uses slash (/) as a path delimiter.  So to use an example like yours, if you create a folder A on the desktop and B within A then that the pathname is A/B.  But in reality, being on your desktop it is /Users/you/A/B, where you is your user id.
    The finder tries to allow as many characters as it can for filenames.  But the slash it cannot allow in a filename when recorded in the file system.  So what it does is actually change the slash to a colon in the actual filename.  Thus the filename "A/B" in the finder is, in reality, "A:B" in the file system.
    I think this colon-equals-slash naming convention is what causing the finder's Compress to treat the name specially and it just changes it the output to be the generic Archive.zip.
    Compress is there as a convenience.  There's lots of other ways to do zips.  There's third party utilities.  There's zip command in the terminal (where you can play the finder's game and generate A:B.zip so that it displays in the finder as A/B.zip).

  • Extension for creating a zip file and unzipping it

    Iam totally new to Dreamweaver and the extensions. So please
    help me with this.
    Assuming i have a .zip file and it contains some html pages
    along with css and gifs.
    The req is to have an Import option, which given this zip
    file, can unzip its contents. The user can work on these html
    pages. When the user finishes working on them, I need an export
    button so that we can package the entire stuff back into a zip
    file.
    How can i implement this ?
    Is there any extension that is available for this ?
    Eagerly looking forward to some useful answers...
    Thanks in advance,
    Ganesh

    There used to be one .. I'm not sure if that was in DMX time
    or DMX 2004
    time .. that, when installed, allowed you to select files
    from the site
    folder or the whole thing and create a zip from them. I don't
    remember what
    it was called or who created it .. but it might be on one of
    my archived
    disks or zips .. I'll try to check it out later today.
    Nancy Gill
    Adobe Community Expert
    Author: Dreamweaver 8 e-book for the DMX Zone
    Co-Author: Dreamweaver MX: Instant Troubleshooter (August,
    2003)
    Technical Editor: DMX 2004: The Complete Reference, DMX 2004:
    A Beginner''s
    Guide, Mastering Macromedia Contribute
    Technical Reviewer: Dynamic Dreamweaver MX/DMX: Advanced PHP
    Web Development
    "Ganesh Ram" <[email protected]> wrote in
    message
    news:engarc$d62$[email protected]..
    > Iam totally new to Dreamweaver and the extensions. So
    please help me with
    > this.
    >
    > Assuming i have a .zip file and it contains some html
    pages along with css
    > and
    > gifs.
    > The req is to have an Import option, which given this
    zip file, can unzip
    > its
    > contents. The user can work on these html pages. When
    the user finishes
    > working on them, I need an export button so that we can
    package the entire
    > stuff back into a zip file.
    >
    > How can i implement this ?
    > Is there any extension that is available for this ?
    >
    > Eagerly looking forward to some useful answers...
    >
    > Thanks in advance,
    > Ganesh
    >
    >

  • Problem with creating a ZIP file

    I have a program that uses java.util.zip to zip all the files in a user's directory (aproximately 7 files totalling 2 MB). When the files are extracted later using WinZip or a similar tool, the files appear to be the same (same file size & date), but they can not be opened by the program that uses them. When I use a binary diff tool to compare the before zip and after zip files, it shows about 20 random bytes that have changed. Anybody else seen this occur?
    Thanks

    Hi,
    I am successfull in putting all the files of a
    directory in a newly created ZIP file. But if my
    directory has a sub-directory, it's not workin....m
    not able to zip it properly. I mean, my program is
    doin it withour error but when i try to open it using
    WinZip...it's giving me an error sayin as not a proper
    archive...
    Do anyone have faced this problem??
    GauzYou need to call the following functions of ZipOutputStream after completing zipping in your code ?
         objZipOutputStream.finish();
         objZipOutputStream.close();Also for every file being zipped, you should to call
    objZipOutputStream.closeEntry()to close that zipEntry.
    Hope this helps.

  • How can i create a zip-file with multiple volumes

    Hi,
    i've to zip a large file (250 MB and more). But the zip file shouldn't be greater than 5 MB, because i have to send the file via E-Mail. So i've thought, that the solution of this problem can be to zip the large file in smaller zip-files, which are multiple volumes of a zip-archive. I've searched very long in WWW, but didn't find something. Perhaps you can help.
    Sorry, about the bad english. :-)
    Timo Bunger

    Hi
    Who said your english is bad ?. OK, are you looking for compressing the 250 MB file in to multiple versions using a java program ?. If not, there is a shareware you can download and split the file into multiple parts by specifying size of each part. You can send these parts via email and the other person can combine these parts into a single file again.
    Find this @
    http://www.freedownloadscenter.com/Utilities/File_Splitting_Utilities/EzSplit.html
    You may need to read a bit about it on how to use.
    Thanks
    Srinivas

  • Creating a zip file from the contents of a directory

    hi, I am having a problem as the title suggests with a zip fil creation...
    using the basic example zip.java i wished to edit it so it doesnt zip a file fro the current directory but rather a directory i inputted.
    It is able to read the first file then throws out the following error with the code below it:
    java.io.FileNotFoundException: test.jpg (The system cannot find the file specified)
    import java.io.*;
    import java.util.zip.*;
    public class Zip {
       static final int BUFFER = 2048;
       public static void main (String argv[]) {
          try
             BufferedInputStream origin = null;
             FileOutputStream dest = new FileOutputStream("C:/Documents and Settings/Phil/My Documents/My Pictures/Work/test.zip");
             CheckedOutputStream checksum = new CheckedOutputStream(dest, new Adler32());
             ZipOutputStream out = new
               ZipOutputStream(new BufferedOutputStream(checksum));
             //out.setMethod(ZipOutputStream.DEFLATED);
             byte data[] = new byte[BUFFER];
             // get a list of files from current directory
             File f = new File("C:/Documents and Settings/Phil/My Documents/My Pictures/Work/");
             f.listFiles();
             String files[] = f.list();
             for (int i=0; i<files.length; i++)
                System.out.println("Adding: "+files);
    FileInputStream fi = new FileInputStream(files[i]);
    origin = new BufferedInputStream(fi, BUFFER);
    ZipEntry entry = new ZipEntry(files[i]);
    out.putNextEntry(entry);
    int count;
    while((count = origin.read(data, 0,
    BUFFER)) != -1)
    out.write(data, 0, count);
    origin.close();
    out.close();
    catch(Exception e)
    e.printStackTrace();
    After investigation i am lead to believe this is because the method returns an array of file and directory names only but not their path and the unqualified names would have therefore be defaulted to the current working directory. Something i understand if this is the case.
    So instead i used the File.listFiles() method to return an array
    of File objects, instead of an array of Strings as shown in the snippet of the changed code below (the changed code highlighted)...but arrived at another error on the second section of highlighted code meaning i cant compile. I cant understand why this is so!
    The error is: "cannot find symbol, Symbol: Contructor ZipEntry (Java.IO.file), location: class.java.util.zip.ZipEntry"
    File f = new File("C:/Documents and Settings/Phil/My Documents/My Pictures/Work/");
             **************File g[] = f.listFiles();***************
             **************String files[] = f.list();**************
             for (int i=0; i<g.length; i++)
                System.out.println("Adding: "+g);
    FileInputStream fi = new FileInputStream(g[i]);
    origin = new BufferedInputStream(fi, BUFFER);
    **************ZipEntry entry = new ZipEntry(g[i]);************
    out.putNextEntry(entry);
    int count;
    while((count = origin.read(data, 0,
    BUFFER)) != -1)
    out.write(data, 0, count);
    origin.close();
    out.close();
    Any help and thoughts most appreciated. Thank u in advance

    I'll admit i took 1 look at that reply an thought "thats stupid that wont work"...
    then a second look an though "actually, i should work i cant believe i didnt think of that"
    Anyways i tried it and it did work
    How are the duke dollars awarded, cos u should have them ordinary_guy
    cheers!

  • Having problems creating a zip file with Japanese language character names

    I have a bunch of files with names in Japanese characters (also Chinese, Korean, Spanish etc, but this will do for an example). The encoding is Unicode.
    I wish to be able to put them in a zip file, then extract them again using any old zip tool (WinZip,PKZip,7-Zip etc)
    Trouble is, every time I do it, the files inside the zipfile end up with garbage character names. The contents of the files are fine, though.
    I'm aware that there used to be a bug in the java.util.zip.* classes regarding character encodings (http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=5bd4fe01ad8a7b4ec89afef5005da?bug_id=4244499) but as far as I can see it's supposed to have been fixed I have also tried the ZipOutputStream class from apache which allows you to set the encoding manually - no luck there either (just many different varieties of garbage characters)
    Test code below. What am I missing here?
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.IOException;
    public class ZipTest {
    static String uniqueFileName = "&#35199;&#12288;&#32020;.txt";
    public static void main(String[] args) {
    try {
    standardZip();
    apacheZip();
    } catch (IOException fe) {
    System.out.println("problem in file - exception " + fe.getMessage());
    public static void apacheZip() throws IOException {
    String encoding = "";
    File inputFile = new File(uniqueFileName);
    FileReader reader = new FileReader(inputFile);
    encoding = reader.getEncoding();
    System.out.println("Using Apache - Encoding = " + encoding);
    File zipFile = new File("apacheZip.zip");
    org.apache.tools.zip.ZipOutputStream zipOutputStream = new org.apache.tools.zip.ZipOutputStream(
    zipFile);
    zipOutputStream.setEncoding(encoding);
    org.apache.tools.zip.ZipEntry zipEntry = new org.apache.tools.zip.ZipEntry(uniqueFileName);
    zipEntry.setSize(inputFile.length());
    zipEntry.setTime(inputFile.lastModified());
    zipOutputStream.putNextEntry(zipEntry);
    int c = 0;
    while (c >= 0) {
    c = reader.read();
    if (c >= 0) {
    zipOutputStream.write(c);
    zipOutputStream.closeEntry();
    zipOutputStream.finish();
    public static void standardZip() throws IOException {
    String encoding = "";
    File inputFile = new File(uniqueFileName);
    FileReader reader = new FileReader(inputFile);
    encoding = reader.getEncoding();
    System.out.println("Using Java IO - Encoding = " + encoding);
    File zipFile = new File("standardZip.zip");
    FileOutputStream zipOut = new FileOutputStream(zipFile);
    java.util.zip.ZipOutputStream zipOutputStream = new java.util.zip.ZipOutputStream(zipOut);
    java.util.zip.ZipEntry zipEntry = new java.util.zip.ZipEntry(uniqueFileName);
    zipEntry.setSize(inputFile.length());
    zipEntry.setTime(inputFile.lastModified());
    zipOutputStream.putNextEntry(zipEntry);
    int c = 0;
    while (c >= 0) {
    c = reader.read();
    if (c >= 0) {
    zipOutputStream.write(c);
    zipOutputStream.closeEntry();
    zipOutputStream.finish();

    Emma_Baillie wrote:
    I have a bunch of files with names in Japanese characters (also Chinese, Korean, Spanish etc, but this will do for an example). The encoding is Unicode.
    I wish to be able to put them in a zip file, then extract them again using any old zip tool (WinZip,PKZip,7-Zip etc)
    Trouble is, every time I do it, the files inside the zipfile end up with garbage character names. The contents of the files are fine, though.This is becuase zip tool doesn't support unicode for zip entries. For example WinZip prior to 11.2 does not support Unicode characters in filenames. You need to look for the simillar information for other tools. You can find more on tools on their website.

  • How can I create a zip file with LabVIEW?

    I would like to compress my data (ASCII format) to an archive.
    I use LVZlib.vi to compress and decompress data but I would like to be able to read the output file with a software archiver such as PowerArchiver/WinZIP.
    Someone knows how I can create a file compatible with zip or gz standard format, thanks !

    >> Yes but I have to install a special archiver (with ms-dos ommand line ability
    >> such as pkzip,arc,rar,arj...) on the computer where I install my LV application.
    Search for "gnu tools for windows" and get zip.exe, gzip.exe, bzip2.exe and others (even the source, if you like). These are about 50kB files that run in place (no installation) - easy to include in a distributed app. Oh, since I'm logged in I'll attach a couple, though I don't have the source on this machine).
    Attachments:
    bin.zip ‏67 KB

  • Creating a Zipped File

    I have developed an application where a user submits large
    graphics files which are then emailed to our client. Is there a way
    that these files can be compressed using WinZip or another
    compression utility) before being emailed? Just got back to using
    Cold Fusion recently and have not been able to find any
    examples/doc on this subject.

    If you're using CF8 you can use <cfzip>
    http://livedocs.adobe.com/coldfusion/8/htmldocs/Tags_u-z_5.html#2851426
    If you're using MX6/7 take a look at these two udf's that use
    java classes to zip/unzip files. They're a bit dated, but it could
    easily be re-written using cffunction/cfargument tags
    http://www.cflib.org/udf.cfm?ID=744
    http://www.cflib.org/udf.cfm?ID=997

  • How do you create an AcrobatXI zip file in windows 8.1?

    How do you create an AcrobatXI zip file in windows 8.1? from acrobat.com docs?  Sorry Not sure what community to ask this in this community?  The email provider I was using didn''t seem to want to accept it through Adobe Send the first time and since Adobe Send ends January 6, I am assuming a zip file is preferable..  I thought I had seen an Adobe Zip file somewhere but haven't been able to locate it. Any help appreciated.
    Thank you.
    Sherrie

    Hi Sherrie L,
    Adobe Send is Adobe's current solution for sending large files. (It's Adobe SendNow that's retiring soon.) Can you tell us what trouble you were running into using Adobe Send?
    There isn't a special version of Zip files for Acrobat, but you could reduce the PDF file size if you have Acrobat. Or, in Windows, you can create a Zip file by choosing File > Send to > Compressed (Zipped) Folder.
    Best,
    Sara

  • 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

  • Want To create Zip file  using java,And Unzip without Java Program

    I want to create a zip text file using java, I know Using ZipOutputStream , we can create a zip file, , But i want to open that zip file without java program. suppose i use ZipOutputStream , then zip file is created But for unZip also difftrent program require. We cant open that zip file without writing diff java program.
    Actually i have one text file of big size want to create zip file using java , and unzip simply without java program.Its Possible??
    Here is one answer But I want to open that file normal way(
    For Exp. using winzip we can create a zip file and also open simply)
    http://forum.java.sun.com/thread.jspa?threadID=5182691&tstart=0

    Thanks for your Reply,
    I m creating a zip file using this program, Zip file Created successfully But when im trying to open .zip file i m getting error like "Canot open a zip file, it does not appear to be valid Archive"
    import java.io.*;
    import java.util.zip.*;
    public class ZipFileCreation
         public static void main (String argv[])
         try {
         FileOutputStream fos = new FileOutputStream ( "c:/a.zip" );
         ZipOutputStream zip = new ZipOutputStream ( fos );
         zip.setLevel( 9 );
         zip.setMethod( ZipOutputStream.DEFLATED );
    //     get the element file we are going to add, using slashes in name.
         String elementName = "c:/kalpesh/GetSigRoleInfo092702828.txt";
         File elementFile = new File ( elementName );
    //     create the entry
         ZipEntry entry = new ZipEntry( elementName );
         entry.setTime( elementFile.lastModified() );
    //     read contents of file we are going to put in the zip
         int fileLength = (int)elementFile.length();
         System.out.println("fileLength = " +fileLength);
         FileInputStream fis = new FileInputStream ( elementFile );
         byte[] wholeFile = new byte [fileLength];
         int bytesRead = fis.read( wholeFile , 0 /* offset */ , fileLength );
    //     checking bytesRead not shown.
         fis.close();
    //     no need to setCRC, or setSize as they are computed automatically.
         zip.putNextEntry( entry );
    //     write the contents into the zip element
         zip.write( wholeFile , 0, fileLength );
         zip.closeEntry(); System.out.println("Completed");
    //     close the entire zip
         catch(Exception e) {
    e.printStackTrace();
    }

Maybe you are looking for