ZipOutputStream problem

hi, im creating zip file which contains two files. The problem is that it will create path folder in the zip where my file is located if im zipping more than one file.
I will give example to make it clear. When my file is located in C:\User\Admin\Desktop\test\file.txt. The zip will contain user folder, admin folder, desktop folder, test folder and then file.txt. which is supposed to be file.txt only. The code works fine if im zipping only one file but when two files this problem will occur.
try {
String [] inFilename = {"C:\\Users\\Desktop\\test\\oral-care-jul.28.2009.0937am.txt","C:\\Users\\Nelson\\Desktop\\RemoveBadWords test\\oral-care-jul.28.2009.0937am.csv"};
String outFilename = "C:\\Users\\Desktop\\test\\outfile3.zip";
                         ZipOutputStream out = new ZipOutputStream( new FileOutputStream(outFilename));
                         for (int i=0; i<inFilename.length; i++) {
                              // Add ZIP entry to output stream.
                              out.putNextEntry(new ZipEntry(inFilename));
                         FileInputStream in = new FileInputStream(inFilename[i]);
                         byte[] buf = new byte[1024];
                         int len;
                         while ((len = in.read(buf)) > 0) {
                         out.write(buf, 0, len);          
                              in.close();
                              out.closeEntry();     
                         out.close();
} catch (IOException e) {
System.out.println(e);
}Please help, how can i get rid of the folder. Thank in advanced.
Edited by: shendel on Jul 28, 2009 11:19 PM
Edited by: shendel on Jul 28, 2009 11:25 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Im little confused, although i think i got what you mean. The full path in out.putNextEntry method is the responsible for the creation of unwanted folder.
For the sake of other below is the working code:
                     try {
                         String [] inFilename = {"C:\\Users\\Desktop\\test\\oral-care-jul.28.2009.0937am.txt","C:\\Users\\Desktop\\RemoveBadWords test\\oral-care-jul.28.2009.0937am.csv"};
                         String outFilename = "C:\\Users\\Desktop\\test\\outfile6.zip";
                       String [] files = {"oral-care-jul.28.2009.0937am.txt","oral-care-jul.28.2009.0937am.csv"};
                         ZipOutputStream out = new ZipOutputStream(
                           new FileOutputStream(outFilename));
                         for (int i=0; i<inFilename.length; i++) {
                              // Add ZIP entry to output stream.
                              out.putNextEntry(new ZipEntry(files));
                         FileInputStream in = new FileInputStream(inFilename[i]);
                         byte[] buf = new byte[1024];
                         int len;
                         while ((len = in.read(buf)) > 0) {
                         out.write(buf, 0, len);          
                              in.close();
                                   out.close();
                    } catch (IOException e) {
                    System.out.println(e);
                    }Thanks for sharing your thought ejp. I really appreciate it. :) cheers..
Edited by: shendel on Jul 29, 2009 1:14 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • Add arabic file names to ZipOutputStream problem

    Dear All,
    i have problem with add arabic file names to ZipOutputStream problem my sample code :
    zipOutputStream.putNextEntry("&#1593;&#1585;&#1576;&#1610;.txt");//some arabic text
    the zip file created successfully and contain files but the files in the zip file with name '??????????.txt'.i use many character set to encode arabic file name such as utf-8,windows-1256,iso-8859-1,IBM437 but the name changed to someting cannot understand lik '_&#1583;_&#1587;_&#1584;_&#1583;_&#1586; ___«___è_&#1585;1.txt' or '??????????.txt'.
    is there anyone to help
    with regards
    Wa'el Abu Rahmeh

    Its a warning. You can ignore it, and your program will run correctly.
    To get the full details, follow the instructions and run it with Xlint:
    javac -Xlint:unchecked beans\CustomerManager.javaProduces this error message:
    beans\CustomerManager.java:19: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.List
                rv.add(getCustomer(String.valueOf(i)));
                      ^
    1 warningIt is a Java1.5 specific warning because you are not using the new Generics info with the collections.
    Here is the version that compiles with no warnings whatsoever.
    package beans;
    import java.util.ArrayList;
    import java.util.List;
    public class CustomerManager
        public List<Customer> getCustomers()
            return generateCustomers();
        private List<Customer> generateCustomers()
            List<Customer> rv = new ArrayList<Customer>();
            for (int i = 0; i < 10; i++)
                rv.add(getCustomer(String.valueOf(i)));
            return rv;
        public Customer getCustomer(String id)
            return new Customer(id, id + "First", "Last" + id,
                "123 Caroline Road Fooville");
    }Basically the change was everywhere you have List or ArrayList replace it with List<Customer> - meaning you have a List of customer objects, rather than just a List of "anything"
    If you are compiling with jdk1.5, then anywhere you use a Collection without specifying the types in this manner, it will create a warning.
    You can ignore the warning if you so wish, and the program should run fine.
    Cheers,
    evnafets

  • File and FileInputStream problem

    Hi all
    I have downloaded from developpez.com a sample code to zip files. I modified it a bit to suit with my needs, and when I launched it, there was an exception. So I commented all the lines except for the first executable one; and when it succeeds then I uncomment the next executable line; and so on. When I arrived at the FileInputStream line , the exception raised. When I looked at the code, it seemed normal. So I want help how to solve it. Here is the code with the last executable line uncommented, and the exception stack :
    // Copyright (c) 2001
    package pack_zip;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import oracle.jdeveloper.layout.*;
    import java.io.*;
    import java.util.*;
    import java.util.zip.*;
    import java.text.*;
    * A Swing-based top level window class.
    * <P>
    * @author a
    public class fzip extends JFrame implements ActionListener{
    JPanel jPanel1 = new JPanel();
    XYLayout xYLayout1 = new XYLayout();
    JTextField szdir = new JTextField();
    JButton btn = new JButton();
    JButton bzip = new JButton();
         * Taille générique du tampon en lecture et écriture
    static final int BUFFER = 2048;
    * Constructs a new instance.
    public fzip() {
    super("Test zip");
    try {
    jbInit();
    catch (Exception e) {
    e.printStackTrace();
    * Initializes the state of this instance.
    private void jbInit() throws Exception {
    this.getContentPane().setLayout(xYLayout1);
         this.setSize(new Dimension(400, 300));
    btn.setText("btn");
    btn.setActionCommand("browse");
    btn.setLabel("Browse ...");
    btn.setFont(new Font("Dialog", 0, 14));
    bzip.setText("bzip");
    bzip.setActionCommand("zipper");
    bzip.setLabel("Zipper");
    bzip.setFont(new Font("Dialog", 0, 14));
    btn.addActionListener(this);
    bzip.addActionListener(this);
    bzip.setEnabled(false);
         this.getContentPane().add(jPanel1, new XYConstraints(0, 0, -1, -1));
    this.getContentPane().add(szdir, new XYConstraints(23, 28, 252, 35));
    this.getContentPane().add(btn, new XYConstraints(279, 28, 103, 38));
    this.getContentPane().add(bzip, new XYConstraints(128, 71, 103, 38));
    public void actionPerformed(ActionEvent e)
    if(e.getActionCommand() == "browse")
    FileDialog fd = new FileDialog(this);
    fd.setVisible(true);
    szdir.setText(fd.getDirectory());
    bzip.setEnabled(true);
    else
              * Compression
         try {
              // création d'un flux d'écriture sur fichier
         FileOutputStream dest = new FileOutputStream("Test_archive.zip");
              // calcul du checksum : Adler32 (plus rapide) ou CRC32
         CheckedOutputStream checksum = new CheckedOutputStream(dest, new Adler32());
              // création d'un buffer d'écriture
         BufferedOutputStream buff = new BufferedOutputStream(checksum);
              // création d'un flux d'écriture Zip
         ZipOutputStream out = new ZipOutputStream(buff);
         // spécification de la méthode de compression
         out.setMethod(ZipOutputStream.DEFLATED);
              // spécifier la qualité de la compression 0..9
         out.setLevel(Deflater.BEST_COMPRESSION);
         // buffer temporaire des données à écriture dans le flux de sortie
         byte data[] = new byte[BUFFER];
              // extraction de la liste des fichiers du répertoire courant
         File f = new File(szdir.getText());
         String files[] = f.list();
              // pour chacun des fichiers de la liste
         for (int i=0; i<files.length; i++) {
                   // en afficher le nom
              System.out.println("Adding: "+files);
    // création d'un flux de lecture
    FileInputStream fi = new FileInputStream(files[i]);
    /* // création d'un tampon de lecture sur ce flux
    BufferedInputStream buffi = new BufferedInputStream(fi, BUFFER);
    // création d'en entrée Zip pour ce fichier
    ZipEntry entry = new ZipEntry(files[i]);
    // ajout de cette entrée dans le flux d'écriture de l'archive Zip
    out.putNextEntry(entry);
    // écriture du fichier par paquet de BUFFER octets
    // dans le flux d'écriture
    int count;
    while((count = buffi.read(data, 0, BUFFER)) != -1) {
              out.write(data, 0, count);
                   // Close the current entry
    out.closeEntry();
    // fermeture du flux de lecture
              buffi.close();*/
    /*     // fermeture du flux d'écriture
         out.close();
         buff.close();
         checksum.close();
         dest.close();
         System.out.println("checksum: " + checksum.getChecksum().getValue());*/
         // traitement de toute exception
    catch(Exception ex) {
              ex.printStackTrace();
    And here is the error stack :
    "D:\jdev32\java1.2\jre\bin\javaw.exe" -mx50m -classpath "D:\jdev32\myclasses;D:\jdev32\lib\jdev-rt.zip;D:\jdev32\jdbc\lib\oracle8.1.7\classes12.zip;D:\jdev32\lib\connectionmanager.zip;D:\jdev32\lib\jbcl2.0.zip;D:\jdev32\lib\jgl3.1.0.jar;D:\jdev32\java1.2\jre\lib\rt.jar" pack_zip.czip
    Adding: accueil188.cfm
    java.io.FileNotFoundException: accueil188.cfm (Le fichier spécifié est introuvable.
         void java.io.FileInputStream.open(java.lang.String)
         void java.io.FileInputStream.<init>(java.lang.String)
         void pack_zip.fzip.actionPerformed(java.awt.event.ActionEvent)
         void javax.swing.AbstractButton.fireActionPerformed(java.awt.event.ActionEvent)
         void javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(java.awt.event.ActionEvent)
         void javax.swing.DefaultButtonModel.fireActionPerformed(java.awt.event.ActionEvent)
         void javax.swing.DefaultButtonModel.setPressed(boolean)
         void javax.swing.plaf.basic.BasicButtonListener.mouseReleased(java.awt.event.MouseEvent)
         void java.awt.Component.processMouseEvent(java.awt.event.MouseEvent)
         void java.awt.Component.processEvent(java.awt.AWTEvent)
         void java.awt.Container.processEvent(java.awt.AWTEvent)
         void java.awt.Component.dispatchEventImpl(java.awt.AWTEvent)
         void java.awt.Container.dispatchEventImpl(java.awt.AWTEvent)
         void java.awt.Component.dispatchEvent(java.awt.AWTEvent)
         void java.awt.LightweightDispatcher.retargetMouseEvent(java.awt.Component, int, java.awt.event.MouseEvent)
         boolean java.awt.LightweightDispatcher.processMouseEvent(java.awt.event.MouseEvent)
         boolean java.awt.LightweightDispatcher.dispatchEvent(java.awt.AWTEvent)
         void java.awt.Container.dispatchEventImpl(java.awt.AWTEvent)
         void java.awt.Window.dispatchEventImpl(java.awt.AWTEvent)
         void java.awt.Component.dispatchEvent(java.awt.AWTEvent)
         void java.awt.EventQueue.dispatchEvent(java.awt.AWTEvent)
         boolean java.awt.EventDispatchThread.pumpOneEvent()
         void java.awt.EventDispatchThread.pumpEvents(java.awt.Conditional)
         void java.awt.EventDispatchThread.run()
    Thank you very much

    One easy way to send a file through RMI is to read all bytes of a file to a byte array and send this array as a parameter of a remote method. But of course you may have problems with memory when you send large files. The receive is simillary.
    Other way is to split the file and getting slices of the file, sending slices and re-assemble at destination. This assume that the file isn't changed through the full transfering is concluded.
    I hope these could help you.

  • Problem with Java and Zip Files

    Hello there everyone. I have a problem with trying to zip up directories with empty folders in them. They zip fine with my code, but according to winzip, the number of files in the archive is incorrect. It's supposed to have a total of 288 files in it, but when it's zipped up, it only says 284. I mention specifically the "empty directories" note because the zipping works fine without empty folders.
    Below is the code for the zip method:
    public static void zip(File[] list, File zipfile, File zipRoot)
         throws IOException {
          if (!zipfile.exists()) {
                   zipfile.createNewFile();
              else if (!zipfile.isFile()) {
                   throw new IOException("The zip file, " + zipfile.getAbsolutePath()
                             + " is not a file.");
              if (list.length == 0) {
                  LOG.error("The list of files to zip up is empty.");
              for (int i = 0; i < list.length; i++) {
                   if (!list.exists()) {
                        throw new IOException("The file or directory, " + list[i].getAbsolutePath()
                                  + " does not exist.");
              FileOutputStream fos = new FileOutputStream(zipfile);
              ZipOutputStream zos = new ZipOutputStream(fos);
              for (int i = 0; i < list.length; i++) {
                   if (LOG.isDebugEnabled())
                        LOG.debug(i + ": " + list[i].getName());
                   String entryName = getRelativeName(list[i], zipRoot);
                   if (list[i].isDirectory()){
                        if (list[i].listFiles().length == 0){
                             ZipEntry entry = new ZipEntry(entryName + "/");
                             zos.putNextEntry(entry);
                   else {
                        ZipEntry ze = new ZipEntry(entryName);
                        zos.putNextEntry(ze);
                        byte[] buffer = new byte[8096];
                        FileInputStream fis = new FileInputStream(list[i]);
                        int read = 0;
                        read = fis.read(buffer);
                        if (LOG.isDebugEnabled())
                        LOG.debug("\tFound " + read + " bytes.");
                        if (read == -1){
                             //empty file, but add it for preservation.
                             //zos.write(buffer,0,0);
                        while (read != -1) {
                             zos.write(buffer, 0, read);
                             read = fis.read(buffer);
                        fis.close();
                        zos.closeEntry();
              zos.close();
    The files look like they're there, but I need the system to be able to determine the number correctly. 
    Here's the interesting thing:  It zips the files, and then when I use the size() method for zip files in java, it says 284 files.  But when I unzip, it says 288 again.  It's like there's files missing when compressed, but when decompressed, they return.  Note that the files are actually there.  If I open the archive in a third party app such as Winzip AND Winrar AND IZarc, they all show 288 files.  Any idea what would make the number of files appear incorrectly in a zip file when zipped by java with the code above?  Thanks in advance.
    - Chris                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    I figured out the problem. When zipping files in windows using winzip, it doesn't explicitly count folders as a "file/folder" as a file in itself. It will create the folders for files to go in, but the folder itself will not be 'counted' when you query the info of the file itself. You have more control of the zip file in java, and can count the folder as a file or not.

  • Problem with file zipping!

    I have problem with my zip files. all that i need is a simple zipping of files. here's is what i am doing
    //this mehod takes 2 arugments, first argument is the file which is to be zipped and the second argument is the name of the zip file
    public void makeZIP(File fileToZip, String zfileName) throws IOException{
    try{
    byte[] buff = new byte[BUF_SIZE];//BUF_SIZE =128
    int cnt=0;
    FileInputStream swcConvFis = new FileInputStream(fileToZip);
    ZipEntry swcConvZipEntry = new ZipEntry(zfileName);
    ZipOutputStream swcConvZipOutputStream = new ZipOutputStream(swcConvFos);
    swcConvZipOutputStream.putNextEntry(swcConvZipEntry);
    while((cnt = swcConvFis.read(buff,0,BUF_SIZE)) != -1){
    swcConvZipOutputStream.write(buff,0,cnt);
    swcConvFis.close();
    swcConvZipOutputStream.closeEntry();
    }catch(NullPointerException npe){npe.printStackTrace();}
    whis code is a part of the servlet code that has to send the zipped file to the applet. What's happening is i am able to zip the files. but when i try to open the zip file it gives me a an error window saying " cannot open file: it does not appear to be valid archive."
    ofcourse the file is zipped on a linux machine and i am trying to open it in windows...it think this shouldn't be a problem though!!
    please somebody throw some light on this. i have searched the archives but not helpful sofar.
    thanks
    sri

    the outputToApplet is the ObjectOutputStream object.
    at the applet's reading end this is what i am doing
    ObjectInputStream intputFromServlet = new ObjectInputStream(connect.getInputStream());
    //code to read the output files from the servlet
    byte[] buff = new byte[BUF_SIZE];
    int cnt = 0;
    ArrayList getOutputFilesFromServlet = (ArrayList) inputFromServlet.readObject(); // at the servlet end i am writing outputToApplet.writeObject(send2Files), send2Files is an ArrayList object that has one .txt file and another .zip file
    System.out.println("total no.of files "+getOutputFilesFromServlet.size()); //shows 2
    Iterator getOutputFilesFromServletIterator = getOutputFilesFromServlet.iterator();
    while(getOutputFilesFromServletIterator.hasNext()){
                   File file = (File)getOutputFilesFromServletIterator.next();
    String fname = file.getName();
    System.out.println("received "+fname);//shows correct file names
                   try{
                        File nfile = new File(getOfile.getParent()+System.getProperty("file.separator")+fname);//puts the files in the requested directory on the client machine
                        FileOutputStream toFile = new FileOutputStream(nfile);
    //reading the files uploaded by the applet
                        while( (cnt = dump.read( buff )) > -1 ){
                             if(cnt<BUF_SIZE){
                             toFile.write( buff, 0, cnt );
                                  toFile.close();
                                  break;
                             toFile.write( buff, 0, cnt );
              }catch(Exception e){e.printStackTrace();}
    System.out.println("finished reading all files from the servlet....");
              }//while(it.next)
    not only the zip file even the other text file is not downloaded properly....(i.e) it shows some junk characters instead of the actual file context. so maybe there is mistake in the way that i am reading the files...but what i am doing at applet's end is just a mirror reflection of what i am doing at the servlet's end. you got me!! hope i am not confusing!
    any suggestions!!

  • Problem with compressing unicode file names in zip file

    Hi Everyone,
    I have a problem while compressing the unicode file name in a zip file. I used the below code for compressing the unicode files.
    String[] source = null;
    // C:\\TestData\\unicode_filename.txt :  unicode_filename.txt is the file created in japanesse language
    source = new String[] {"C:\\TestData\\temp_properties.xml","C:\\TestData\\unicode_filename.txt" };
    byte[] buf = new byte[1024];
    // Create the ZIP file
    String target = "C:\\TestData\\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.
         String fileName;
         File tempFile;
         ZipEntry zipEntry = new ZipEntry(source[i]);
         fileName = zipEntry.getName();
    zipEntry = new ZipEntry(fileName);
    zipEntry.setMethod(ZipEntry.DEFLATED);
    getUTF8Bytes(source[i]);
    // here I'm unable to find the unicode files and not able to understand.
    out.putNextEntry(zipEntry);
    // 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();Please help me how to fix this issue.
    Thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Hi,
    Thanks for your time for looking into my query.
    Please check the below code for debugging the issue and throw your comments/suggestions for fixing the issue.
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    public class ZipTest
      public static void main(String[] args) {
              String[] source = new String[] {"C:\\TestData\\APP_Properties.xml","C:\\TestData\\??.txt" };
              byte[] buf = new byte[1024];
              try {
                   // Create the ZIP file
                   String target = "C:\\TestData\\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.
                        String fileName;
                        File tempFile;
                        ZipEntry zipEntry = new ZipEntry(source[i]);
                        fileName = zipEntry.getName();
                        zipEntry = new ZipEntry(fileName);
                        zipEntry.setMethod(ZipEntry.DEFLATED);
                        getUTF8Bytes(source[i]);
                        out.putNextEntry(zipEntry);
                        // 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) {
                   e.printStackTrace();
         private static byte[] getUTF8Bytes(String s) {
              char[] c = s.toCharArray();
              FileOutputStream file;
              try {
                   file = new FileOutputStream("C:\\TestData\\output.txt", true);
                   int len = c.length;
                   // Count the number of encoded bytes...
                   int count = 0;
                   for (int i = 0; i < len; i++) {
                        int ch = c[i];
                        if (ch <= 0x7f) {
                             count++;
                        } else if (ch <= 0x7ff) {
                             count += 2;
                        } else {
                             count += 3;
                   // Now return the encoded bytes...
                   byte[] b = new byte[count];
                   int off = 0;
                   for (int i = 0; i < len; i++) {
                        int ch = c[i];
                        if (ch <= 0x7f) {
                             b[off++] = (byte) ch;
                             file.write((byte) ch);
                        } else if (ch <= 0x7ff) {
                             b[off++] = (byte) ((ch >> 6) | 0xc0);
                             file.write((byte) ((ch >> 6) | 0xc0));
                             b[off++] = (byte) ((ch & 0x3f) | 0x80);
                             file.write((byte) ((ch & 0x3f) | 0x80));
                        } else {
                             b[off++] = (byte) ((ch >> 12) | 0xe0);
                             file.write((byte) ((ch >> 12) | 0xe0));
                             b[off++] = (byte) (((ch >> 6) & 0x3f) | 0x80);
                             file.write((byte) (((ch >> 6) & 0x3f) | 0x80));
                             b[off++] = (byte) ((ch & 0x3f) | 0x80);
                             file.write((byte) ((ch & 0x3f) | 0x80));
                   file.write((byte) '\n');
                   file.write((byte) '\r');
                   file.flush();
                   file.close();
                   return b;
              } catch (FileNotFoundException e1) {
                   e1.printStackTrace();
              } catch (IOException e1) {
                   e1.printStackTrace();
              return null;
    }Thanks
    Aravind                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • A strange problem using the zip files

    I'm currently working on a university project with another student in which we use zip files (using the java ZipFile , and ZipOutputStream classes), we write certain data to a zip file (and verify that it is there by checking the disk). and later we read the zip file, and write it back , appending some data at the end of the file.
    although we see the changes actually take place on the disk , in one of the cases when reading the data we don't see the data we have appended before (although it is physically written on the disk).
    testing has revealed that this has something to do with the rename command or java being unsynchronized with the data actually on the disk (caching problem?).
    we use this code to preform the process:
    ZipFile zf= new ZipFile( ((Integer)lexicon.get(keyword)).intValue()+".zip");
              BufferedInputStream input= new BufferedInputStream(zf.getInputStream(new ZipEntry("data")));
              // create a temporary new zip file.
              ZipOutputStream zipst= new ZipOutputStream(new FileOutputStream( ((Integer)lexicon.get(keyword)).intValue()+".tmp.zip"));
              BufferedOutputStream output =new BufferedOutputStream(zipst);
              zipst.putNextEntry(new ZipEntry("data"));
              // stream the contents of the old file into the new file
              //(we do it this way because of the inability of the java zip file interfaces to add to an existing zip file)
              int current = input.read();
              while(current!=-1){
              output.write(current);
              current = input.read();
              output.write(entry.getBytes(false)); // add the new entrys.
              output.flush();
              zipst.closeEntry();
              output.close();
              // erase the old file.
              File toErase = new File( ((Integer)lexicon.get(keyword)).intValue()+".zip");
              toErase.delete();
              // rename the temporary file to the old files name.
              File toRename = new File( ((Integer)lexicon.get(keyword)).intValue()+".tmp.zip");
              toRename.renameTo(new File( ((Integer)lexicon.get(keyword)).intValue()+".zip"));
    we use:
    1. j2sdk 1.4.2_05
    2. running under libranet linux.
    any help will be appreciated

    the data does indeed get lost in the course fo rewriting the file, e assume this is some sort of synchronization issue with java and the file system.
    addig enteies to an existing zip file would have been great, if we had it a few weeks ago , we had to make do without this ability , and all of the code is already written and mostly working (except for the problem I mention) and we don't really want to rewrite the zip file access.
    additional testing has shown that the data gets lost when we use the rename command.
    very strange...
    thanks for the input

  • Problem in delete folder

    Please don't refer me to the innumeras delete folder solutions available in the SDN. None of them has come to my help.
    I need to delete a folder. Well, codes are available everywhere, I run it, it successfully deletes the folder specified.
    But the requirement is, I need to make a zip of the folder, then I'll delete the original folder. I am pasting the code here. The zip part is working, the delete part is not! if you comment the line calling zip, it deletes the folder, but after zipping, it cannot delete.
    Is there some lock present? How to check and remove that? Please help.
    * Created on Jan 16, 2006
    * To change the template for this generated file go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    package com.ibm.eis.printapi;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.PrintStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    * @author localusr
    * To change the template for this generated type comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    class PrintUtils {
         static String folderName = "EISMENU_bak";
         static String path = "c:\\samik";
         static String outFilename = "outfile.zip";
         public static void main(String args[]) throws IOException {
              File inFileName = new File(path + "\\" + folderName);
              //make the zip file
              makeZip(inFileName, path, outFilename);
              //Now, delete the directory
              File inFileName2 = new File(path + "\\" + folderName);
              inFileName2.renameTo(new File(path + "\\" + "aaa"));
              deleteDir(inFileName2);
         public static void makeZip(File inFile, String path, String outFile) throws IOException {
              File[] filenames = inFile.listFiles();
              byte b[] = new byte[512];
              ZipOutputStream out = null;
              try {
                   out = new ZipOutputStream(new FileOutputStream(path + "\\" + outFilename));
                   for (int i = 0; i < filenames.length; i++) {
                        if (filenames.isFile()) {
                             InputStream in = new FileInputStream(filenames[i]);
                             ZipEntry e = new ZipEntry(filenames[i].toString().replace(File.separatorChar, '/'));
                             out.putNextEntry(e);
                             int len = 0;
                             while ((len = in.read(b)) != -1) {
                                  out.write(b, 0, len);
                             print(e);
              } catch (IOException ioe) {
                        ioe.printStackTrace();
              } finally {
                   out.close();
                   out = null;
                   filenames = null;
                   b = null;
         public static void print(ZipEntry e) {
              PrintStream sop = System.out;
              sop.print("added " + e.getName());
              if (e.getMethod() == ZipEntry.DEFLATED) {
                   long size = e.getSize();
                   if (size > 0) {
                        long csize = e.getCompressedSize();
                        long ratio = ((size - csize) * 100) / size;
                        sop.println(" (deflated " + ratio + "%)");
                   } else {
                        sop.println(" (deflated 0%)");
              } else {
                   sop.println(" (stored 0%)");
         public static boolean deleteDir(File dir) {
              boolean deleted = false;
              try {
                   if (dir.isDirectory()) {
                        String[] children = dir.list();
                        for (int i = 0; i < children.length; i++) {
                             boolean success = deleteDir(new File(dir, children[i]));
                             if (!success) {
                                  deleted = false;
                             } else {
                                  deleted=true;
                   // The directory is now empty so delete it
                   //System.out.println(dir.canRead())
                   deleted = dir.delete();
              } catch (Exception e) {
                   System.out.println("error: " + e);
              return deleted;

    Thanks it worked.
    The problem was, the folder I was trying to delete had .classpath, .project, .websettings files. It was encountering problem to delete these files because it internally also uses files of same name.
    May be that was the reason.
    I tried with any other folder, it worked.

  • 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...)

  • Problems with CRC in some windows app's whit zip files generated with Java

    Hello,
    That is very strange but, we have an app for compressing a folder into a zip. For making, we use the Java.Util.Zip API. Our zip file looks fine, we can unzip the files into another folder without problems, even we can open the file with Winzip or Winrar.
    But, we had encountered problems with anothers win apps like "Recovery ToolBox", or another win app built with the "Dynazip.dll" library. This apps give us the next error.
    "Bad Crc".
    But if we unzip this "corrupt" file and we zip the content again, all work without errors.
    [http://img297.imageshack.us/i/dibujoou.jpg/]
    Our code (this function only zips a single file):
        public static File zipFile(String sFile, String sNameFileIn, String sFileOut)
                throws IOException {
            File file = new File(sFile);
            FileOutputStream out = new FileOutputStream(sFileOut);
            FileInputStream fin = new FileInputStream(file);
            byte[] fileContent = new byte[(int) file.length()];
            fin.read(fileContent);
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            ZipOutputStream zout = new ZipOutputStream(bout);
            ZipEntry zipEntry = new ZipEntry(sNameFileIn);
            zout.putNextEntry(zipEntry);
            zout.write(fileContent, 0, fileContent.length);
            zout.closeEntry();
            zout.finish();
            zout.flush();
            zout.close();
            out.write(bout.toByteArray());
            out.flush();
            out.close();
            File fich = new File(sFileOut);
            fin.close();
            return fich;
        }I try to calculate the crc number for my own without success... I don't know what's happening
    Thanks in advance

    FileOutputStream out = new FileOutputStream(sFileOut);ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(sFileOut));
    byte[] fileContent = new byte[(int) file.length()];Here you are assuming the file size is <= Integer.MAX_VALUE. What if it isn't? Remove.
    fin.read(fileContent);Here you are assuming you filled the buffer. There is nothing in the API specification to warrant that assumption. Remove. See below.
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ZipOutputStream zout = new ZipOutputStream(bout);Remove.
    ZipEntry zipEntry = new ZipEntry(sNameFileIn);
    zout.putNextEntry(zipEntry);Correct.
    zout.write(fileContent, 0, fileContent.length);int count;
    byte[] buffer = new byte[8192];
    while ((count = fin.read(buffer)) > 0)
    zout.write(buffer, 0, count);
    zout.closeEntry();Correct.
    zout.finish();
    zout.flush();Redundant but not incorrect.
    zout.close();Correct.
    out.write(bout.toByteArray());
    out.flush();
    out.close();Remove.
    File fich = new File(sFileOut);
    fin.close();
    return fich;I don't know why this method returns a File constructed out of one of its own arguments, which the caller could equally well do for himself, otherwise OK.

  • Content type problem for 'does not appear to be a proper arcive'

    Hi all,
    The following code will create a ZipOutputStream using ByteArrayOutputStream (not FileOutputStream) and attach the outputstream to a MIME multipart email using ByteArrayDataSource (so the file never exists physically).
    It works and sends the email but the zip 'does not appear to be a valid archive' even though it looks about the right size. If I do the same and use FileOutputStream to create a physical file it works OK. I think it is an issue with the content type, or maybe this just isn't possible!
    I have tried:
    byteArray.toByteArray(),
    byteArray.toString().getBytes() and application/zip & application/unknown.
    Can anyone help or suggest an alternative way to create a 'in-memory' zip file that can then be emailed?
    Many thanks
        // Specify files to be zipped
                                                                 String[] filesToZip = new String[3];
                                                                 filesToZip[0] = "C:\\Program Files\\NetBeans3.6\\firstfile.txt";
                                                                 filesToZip[1] = "C:\\Program Files\\NetBeans3.6\\secondfile.txt";
                                                                 filesToZip[2] = "C:\\Program Files\\NetBeans3.6\\thirdfile.txt";
                                                                 byte[] buffer = new byte[18024];
                                                                 // Specify zip file name
                                                                  String zipFileName= eq_rt.getReportName() + ".zip";
                                                                 try {
                                                                   // Create ZipOutputStream to store the FileOutputStream
                                                                   //ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
                                                                   ByteArrayOutputStream byteArray = new ByteArrayOutputStream();                                                             
                                                                   ZipOutputStream out = new ZipOutputStream(byteArray);                                                              
                                                                   // Set the compression ratio
                                                                   out.setLevel(Deflater.DEFAULT_COMPRESSION);
                                                                   // iterate through the array of files, adding each to the zip file
                                                                   for (int a = 0; a < filesToZip.length; a++) {
                                                                     System.out.println(a);
    //                                                                 // Associate a file input stream for the current file
                                                                     FileInputStream in = new FileInputStream(filesToZip[a]);
                                                                     // This ROCKS as it is passing a array into the text file .getBytes() seems
                                                                     // to be the KEY in getting ByteArrayInputStream to WORK
                                                                     String strSocketInput = "TAIWAN";
                                                                     ByteArrayInputStream baIn = new ByteArrayInputStream(strSocketInput.getBytes());
                                                                     //ByteArrayInputStream baIn = new ByteArrayInputStream( getAttachementNoFormat(eq_rt.getStoredProc() ) );                                                               
                                                                     // Add ZIP entry to output stream.
                                                                     out.putNextEntry(new ZipEntry(filesToZip[a]));
                                                                     // Transfer bytes from the current file to the ZIP file
                                                                     int len;
                                                                     while ((len = baIn.read(buffer)) > 0)
                                                                     out.write(buffer, 0, len);
                                                                     // Close the current entry
                                                                     out.closeEntry();
                                                                     // Close the current file input stream
                                                                     baIn.close();                                                   
                                                                  // DataSource sourcezip = new FileDataSource(zipFileName);
                                                                   //DataSource sourcezip = new ByteArrayDataSource(byteArray.toByteArray(), zipFileName, "application/octet-stream");   
                                                                    DataSource sourcezip = new ByteArrayDataSource(byteArray.toByteArray(), zipFileName, "application/octet-stream" );
                                                                   // Create a new MIME bodypart
                                                                   BodyPart attachment = new MimeBodyPart();
                                                                   attachment.setDataHandler(new DataHandler(sourcezip));
                                                                   attachment.setFileName(zipFileName);                       
                                                                   /* attach the attachemnts to the mail */
                                                                   multipart.addBodyPart(attachment);                                                                
                                                                   // Close the ZipOutPutStream
                                                                   out.close(); 

    Many thanks Dr Clap. Moving the Closing the ZipOutputStream before I attached it to the email solved my problem.
                                          /* Close the ZipOutPutStream (very important to close the zip before you attach it to the email) Thanks DrClap */
                                                                    out.close();                                                    
                                                                    /* Create a datasource for email attachment */
                                                                    // DataSource sourcezip = new FileDataSource(zipFileName);
                                                                    DataSource sourcezip = new ByteArrayDataSource(byteArray.toByteArray(), zipFileName, "application/zip" );
                                                                    /* Create a new MIME bodypart */
                                                                    BodyPart attachment = new MimeBodyPart();
                                                                    attachment.setDataHandler(new DataHandler(sourcezip));
                                                                    attachment.setFileName(zipFileName);                       
                                                                    /* attach the attachemnts to the mail */
                                                                    multipart.addBodyPart(attachment);  

  • Problem with chinese fileNames inside a zipfile

    Hi all
    I have a really strange problem . I needed to create a zip file(English name) and add a chinese file to that Zip . I had done this using java.uti.zip and in the output zip file i am seeing a totally different chiense name than what i had expected . My code looks like this
    String fileName = "������";(Chinese fileName)
    File zipFile = new File("abc.txt");
    ZipOutputStream zipOutStrm = null;
    BufferedInputStream in = null;
    try
    int length = 0;
    byte[] buffer = new byte[2048];
    zipOutStrm = new ZipOutputStream(new FileOutputStream("abc.zip"));
    ZipEntry zipe = new ZipEntry(fileName);
    zipOutStrm.putNextEntry(zipe);
    in = new BufferedInputStream(new FileInputStream(zipFile));
    length = in.read(buffer);
    while(length != -1)
    zipOutStrm.write(buffer, 0, length);
    length = in.read(buffer);
    catch(FileNotFoundException e)
    e.printStackTrace();
    catch(IOException e)
    e.printStackTrace();
    finally
    try
    in.close();
    zipOutStrm.closeEntry();
    zipOutStrm.close();
    catch(Exception e)
    //do nothing ;
    Later i found out from the sun site that there is some encoding issues with the way java does the zip and winZip encoding .
    Can any one let me know how to come out of this ??

    The file name encoding issue with ZIP is basically: The encoding of file names in ZIP-files is not specified and when non-ASCII file names came along each and every zip-utility solved it in a different way, some did not solve it at all, some store it in ISO-8859-1 (= no chinese), some store it in UTF-8 (I think Java does this), others might have other strategies ...
    So if there is a way to not use non-ASCII characters in your zip-files you greatly enhance the portability of your programm.

  • Problem with the streams....

    Dear All,
    I am trying to zip a file in the client side and sending it to the server side machine......there, i am trying to unzip it and writting it over there...for this, i am using a seperate program in the client side and in the server side.................................
    In the client program, after opening all the necessary streams and all formalities, i am using the code...
    "InputStream in = urlconnection.getInputStream();
    while (in.read()!=-1);"
    only if i use the above code, the zipped file is transfered to my server machine...but in this case, the link with the server is not getting disconnected...i mean the command prompt remains alive, without stopping...what i inferred is, my control is got into the above said "InputStream in = urlconnection.getInputStream();"...indefinitely...
    so i tried of removing the above said statement.....in this case, the zipped file is NOT getting written in my server machine....
    what to do???
    any suggestions please...waiting for the reply very anxiously, refreshing this site for every 2 minutes....
    sakthivel s.
    snippet code for ur reference...
    Client side
    try
    ZipOutputStream zipoutputstream = new ZipOutputStream(urlconnection.getOutputStream());
    ZipEntry zipentry = new ZipEntry(filename);
    zipentry.setMethod(ZipEntry.DEFLATED);
    zipoutputstream.putNextEntry(zipentry);
    byte bytearray[] = new byte[1024];
    File file = new File(filenamedir);
    FileInputStream fileinputstream = new FileInputStream(file);
    BufferedInputStream bufferedinputstream = new BufferedInputStream(fileinputstream);
    int length = 0;
    while((length=bufferedinputstream.read(bytearray)) != -1)
    zipoutputstream.write(bytearray,0,length);
    fileinputstream.close();
    bufferedinputstream.close();
    zipoutputstream.flush();
    zipoutputstream.finish();
    zipoutputstream.closeEntry();
    zipoutputstream.close();
    InputStream in = urlconnection.getInputStream();
    while (in.read()!=-1); // the said while loop....................
    System.runFinalization();
    urlconnection.getInputStream().close();
    urlconnection.disconnect();
    the way of connecting witht the server : (just a snippet of the code)
    URL serverURL = new URL("http://192.168.10.55:8001/servlet/uploadservlet");
    HttpURLConnection.setFollowRedirects(true);
    urlconnection= (HttpURLConnection)serverURL.openConnection();
    urlconnection.setDoOutput(true);
    urlconnection.setRequestMethod("POST");
    urlconnection.setDoOutput(true);
    urlconnection.setDoInput(true);
    urlconnection.setUseCaches(false);
    urlconnection.setAllowUserInteraction(true);
    urlconnection.setRequestProperty("Cookie",cookie);
    urlconnection.connect();
    Server Side:
    javax.servlet.ServletInputStream servletinputstream = httpservletrequest.getInputStream();
    ZipInputStream zipinputstream = new ZipInputStream(servletinputstream);
    ZipEntry zipentry = null;
    String directory="c:\\test"; // the unzipped file should be written to this directory...
    try
    File file = new File(directory);
    if(!file.exists())
    file.mkdirs();
    catch(Exception exp)
    {System.out.println("I am from Server: " + exp);}
    try
    zipentry = zipinputstream.getNextEntry();
    if(zipentry != null)
    int slash = zipentry.getName().lastIndexOf(File.separator) + 1;
    String filename = zipentry.getName().substring(slash);
    File file1 = new File(directory + File.separator + filename);
    FileOutputStream fostream = new FileOutputStream(file1);
    BufferedOutputStream bufferedoutputstream = new BufferedOutputStream(fostream);
    byte abyte0[] = new byte[1024];
    for(int index = 0; (index = zipinputstream.read(abyte0)) > 0;)
    bufferedoutputstream.write(abyte0, 0, index);
    servletinputstream.close();
    bufferedoutputstream.flush();
    bufferedoutputstream.close();
    zipinputstream.closeEntry();
    zipinputstream.close();
    fostream.flush();
    fostream.close();
    catch(IOException ioexception)
    {System.out.println("IOException occured in the Server: " + ioexception);ioexception.printStackTrace();}
    P.S: I am not getting any error in the server side or cleint side...the only problem is, the command prompt(where i am running my cleint program) is getting standing indefinitely...i have to use control-c to come to the command prompt again...this is because of the while looop said in the client machine....if i remove it...the file is not gettting transfered...what to do????

    Some thoughts:
    1) please quote your code so it's readable (see http://forum.java.sun.com/faq.jsp#messageformat ).
    2) why are you calling "System.runFinalization();"?
    3) Offhand I don't see where the read would ever stop. It's waiting for an end of input from the server, but the server doesn't even begin to write output to it. What happens when you connect to your server with a browser or some other client?
    4) is it really wise to read and write one byte at a time?

  • Problem in creating zip file.

    Hi,
    I am using the zip package to create a zip file.The code is given below :
      ZipOutputStream out = new ZipOutputStream(new
      BufferedOutputStream(new FileOutputStream("d:\\abc\\target.zip")));
        byte[] data = new byte[1000];              
        BufferedInputStream in = new BufferedInputStream
    (new FileInputStream("d:\\abc\\xyz.log"));
        int count;
       out.putNextEntry(new ZipEntry("d:\\abc\\target.zip"));
       while((count = in.read(data,0,1000)) != -1)
       out.write(data, 0, count);
       in.close();
       out.flush();
       out.close();The problem is that the zip file created is having no files when i try to zip files from locations other than the program file location ie other than current drive.
    Could you please suggest me a solution so that it zips file from any location. Thanks in advance.

    BRAVO wrote:
    Hi,
    I am using the zip package to create a zip file.The code is given below :
    ZipOutputStream out = new ZipOutputStream(new
    BufferedOutputStream(new FileOutputStream("d:\\abc\\target.zip")));
    byte[] data = new byte[1000];              
    BufferedInputStream in = new BufferedInputStream
    (new FileInputStream("d:\\abc\\xyz.log"));
    int count;
    out.putNextEntry(new ZipEntry("d:\\abc\\target.zip"));
    while((count = in.read(data,0,1000)) != -1)
    out.write(data, 0, count);
    in.close();
    out.flush();
    out.close();The problem is that the zip file created is having no files when i try to zip files from locations other than the program file location ie other than current drive.
    Could you please suggest me a solution so that it zips file from any location. Thanks in advance.My advice would be to tryout something as given below and checkout whether that can
    a). Give you Exception Message/stack trace if an error has occured
    b). Check whether the appropriate code change works
    public compressFile(String inputFile,String destFile){
    ZipOutputStream out = null;
    byte[] data = null;
    BufferedInputStream in = null;
    try{
        out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destFile)));
        data = new byte[1024];
         try{               
             in = new BufferedInputStream(new FileInputStream(inputFile));
             int count = -1;
             out.putNextEntry(new ZipEntry(inputFile));
             while((count = in.read(data)) > 0){     
                out.write(data, 0, count);
           }catch(Exception e){
               System.err.println(e.getMessage());
               e.printStackTrace();
           }finally{       
                  if(in != null)
                     try{in.close();}catch(Exception ex){}
       out.flush();
    }catch(Exception exp){
        System.err.println(exp.getMessage());
        exp.printStackTrace();
    }finally{
      if(out != null)
         try{out.close();}catch(Exception e){}
       out = null;
       in = null;
    }in order to compress the file we can call the method something like
    compressUtilObj.compressFile("d:\\abc\\target.zip","d:\\abc\\xyz.log");Hope that helps :)
    REGARDS,
    RaHuL

  • Problem with zipping file with chinese chars

    I need to zip a html page which contains some chinese characters, I am able to zip it and create a zip file
    but the problem is when i open the zip file and view the html file it displays junk characters instead
    of chinese characters
    Here is what i am doing
      ByteArrayOutputStream bStream = new ByteArrayOutputStream();
       ZipOutputStream zStream = new ZipOutputStream(bStream);
        ZipEntry zipEntry = new ZipEntry(htmlFilename);
        zStream.putNextEntry(zipEntry);
        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
        PrintWriter writer = new PrintWriter(
                               new OutputStreamWriter(dataStream,"UTF-8"));
    writer.write(htmlString); //htmlString is the string which contents the html contents which has chinese char
        writer.close();
    zStream.write(dataStream..toByteArray());

    And when you view the unzipped file, are you using something that realizes that you encoded your data using UTF-8? My guess is that you are not.
    PC&#178;

Maybe you are looking for

  • How do I access the firewall in Airport Extreme?

    Hello, this may be a very stupid question, but how do I access the firewall in my brand new Airport Extreme?  According to the Apple specifications, it contains a built-in firewall, yet I cannot find any mention of this when using Airport Utility to

  • Connecting a vga monitor

    Well I have never had a MAC before and now starting to wish I never bothered wasting my mony The whole idea of the mac mini was perfect for my situation as I have a number of PC's around the house with monitors. None of my monitors will work with it

  • Add Fields in CUP Request - SAP GRC Access Control 5.3

    Dear Friends, I am wondering on how to add fields value in CUP (Compliant User Provisioning) SAP GRC AC 5.3. Currently i'm leading 9 SAP Security Coordinators in Indonesia and i want to create Performance Metrics on how long the CUP Requests is proce

  • Wls server

    Hi I have WLS running with one admin and 2 managed servers. Right now the servers are started from the command prompt , so I can look at the console and know what is happening in the system We would like to make it run like as a windows service, but

  • Error add a new appset

    Hello everyone, I am working with BPC 7.5 MS SP 04. When i try to make a copy of the appset, i have an error in the step "copy olap database". Any ideas? Thank you very much Simone