Append to Zip file

Hi everyone,
I have created a zip file (test.zip), but i cant figure out how to append a text file to it.
Can anybody help?

http://java.sun.com/j2se/1.5.0/docs/api/java/util/zip/ZipInputStream.html#createZipEntry(java.lang.String)

Similar Messages

  • How to append to zip files

    I would like to know how to append to a zip file, I know how to write a zip file and I can put as many entries in the first time but if I run my program again and try to add a file to the same zip file it erases what was already in it. I use ZipOutputStream(new FileOutputStream), I have tried the FileOutputStream append but it does not seem to work for zip files, I have tried RandomAccessFile on my zip file but that just seems to add the bytes to the file that already in the zip file, and makes the file unopenable, corrupt. If you can help, please tell me how.

    You actually have to open the previous zipped file, read it's entries and their data and then rewrite a new zip file with these entries and their data. You can then delete your first file and rename the new one so the effect is that you have "appended" zip files to the existing archive.
    Here is an example which I pieced together from a larger bit of code that I have. This would need to be in a try/catch but this should give you a start.
    /** This method adds a new file to an existing zip file. It * includes all the zipped entries previously written.
    * @param file The old zip archive
    * @param filename The name of the file to be Added
    * @param data The data to go into the zipped file
    * NOTE: This method will write a new file and data to an archive, to
    * write an existing file, we must first read the data frm the file,
    * then you could call this method.
    public void addToArchive(File file, String filename, String data)
         ZipOutputStream zipOutput = null;
    ZipFile zipFile = null;
    Enumeration zippedFiles = null;
    ZipEntry currEntry = null;
    ZipEntry entry = null;
    zipFile = new ZipFile( file.getAbsolutePath() );
         //get an enumeration of all existing entries
    zippedFiles = zipFile.entries();
         //create your output zip file
    zipOutput = new ZipOutputStream( new FileOutputStream ( new File( "NEW" + file.getAbsolutePath() ) ) );
    //Get all the data out of the previously zipped files and write it to a new ZipEntry to go into a new file archive
    while (zippedFiles.hasMoreElements())
    //Retrieve entry of existing files
    currEntry = (ZipEntry)zippedFiles.nextElement();
    //Read data from existing file
    BufferedReader reader = new BufferedReader( new InputStreamReader( zipFile.getInputStream( currEntry ) ) );
    String currentLine = null;
    StringBuffer buffer = new StringBuffer();
    while( (currentLine = reader.readLine() ) != null )
    buffer.append( currentLine);
    //Commit the data
    zipOutput.putNextEntry(new ZipEntry(currEntry.getName()) ) ;
    zipOutput.write (buffer.toString().getBytes() );
    zipOutput.flush();
    zipOutput.closeEntry();
    //Close the old zip file
    zipFile.close();
    //Write the 'new' file to the archive, commit, and close
    entry = new ZipEntry( newFileEntryName );
    zipOutput.putNextEntry( entry );
    zipOutput.write( data.getBytes() );
    zipOutput.flush();
    zipOutput.closeEntry();
    zipOutput.close();
         //delete the old file and rename the new one
    File toBeDeleted = new File ( file.getAbsolutePath() );
    toBeDeleted.delete();
         File toBeRenamed = new File ( "NEW" + file.getAbsolutePath() );
    toBeRenamed.rename( file );
    Like I said I haven't tested this code as it is here but hopefully it can help. Good luck.

  • Appending files to zip files

    Hi,
    My requirement is i have to append data to zip files using file receiver adapter.
    am also using FCC.
    can anybody help me on this how to approach.
    -Kishore
    Edited by: Kishore_Kumar_XI on Mar 3, 2012 6:05 PM

    Hi,
    I think you can use my blog case for your scenario
    ABAP PROXY TO FILE – Handling Heavy Volumes in SAP PI (ABAP PROXY TO FILE u2013 Handling Heavy Volumes in SAP PI)
    Steps:
    1. split into two scenario
         proxy --> XI --> file    (using above blog concept)
         (ii) file (zipped) --> Xi --> FTP (file) without IR objects
    using the first scenario write the file to XI server internal file location using NFS protocol using file receiver channel in append mode.
    Use the scripts as mentioned in the above blog (Note:- scripts will differ depending on XI Operating System). In the second script i.e.,  "Run OS Command After Message Processing" script, add the extra functionality which can zip and rename the file when it is last transaction. The last transaction can be identified from ABAP proxy message with little extra functionality in the report and using dynamic configuration we can pass this as input to second script which does the zipping and renaming.
    We are renaming the file for the last transaction, so that it can be pooled by second scenario file sender channel which will pool with the same naming convention. Pass this zip file directly to FTP server without using any IR objects.
    Regards,
    Praveen Gujjeti

  • ZipOutputStream appends characters to beginning of zipped file?

    Hi and thanks in advance for any help!
    I am trying to zip Excel files using ZipOutputStream class. I can open the Excel files fine before I zip. Then I run my program to zip. It seems to work. I use WinZip to unzip and when I try and open unzipped file in Excel, Excel says it does not recognize format. Looking at unzipped file in text editor, about 15 wierd characters and nulls are now appended to the beginning of my Excel file that are not in the original. If I delete them in the text editor, Excel can open.
    Here is my zip code:
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ArrayList fileNames = new ArrayList();
    fileNames.add ("91PSAG0Jak.csv");
    fileNames.add ("91I9F60K62.csv");
    // Compress the files
    for (int i=0; i<2; i++) {
    String filename = String.valueOf(fileNames.get(i));
    byte[] file = DatabaseUtilities.downloadFile("pdfstoragedir", filename);
    // Add ZIP entry to output stream.
    zos.putNextEntry(new ZipEntry(filename));
    ObjectOutputStream oos = new ObjectOutputStream (zos);
    oos.writeObject(file);
    oos.flush();
    // Complete the entry
    zos.closeEntry();
    //Complete the ZIP file
    zos.close();
    byte[] zipFile = baos.toByteArray();
    DatabaseUtilities.uploadFile("pdfstoragedir", "zipOutput.zip", zipFile);
    FileOutputStream fos = new FileOutputStream("C:\\zipOutput.zip");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    bos.write(zipFile, 0, zipFile.length);

    Thanks, I got it I think, I can write my byte[] directly to the zipOutputStream:
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ArrayList fileNames = new ArrayList();
    fileNames.add ("8aCeOH0Fba.zip");
    fileNames.add ("8da6S40H4e.zip");
    // Compress the files
    for (int i=0; i<2; i++) {
    String filename = String.valueOf(fileNames.get(i));
    byte[] file = DatabaseUtilities.downloadFile("pdfstoragedir", filename);
    // Add ZIP entry to output stream.
    zos.putNextEntry(new ZipEntry(filename));
    zos.write(file);
    // Complete the entry
    zos.closeEntry();
    //Complete the ZIP file
    zos.close();
    byte[] zipFile = baos.toByteArray();
    DatabaseUtilities.uploadFile("pdfstoragedir", "zipOutput.zip", zipFile);
    FileOutputStream fos = new FileOutputStream("C:\\zipOutput.zip");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    bos.write(zipFile, 0, zipFile.length);

  • Jar files downloaded from SkyDrive are being renamed to jar.zip files

    I have cut and pasted the following series of exchanges from when I posted the problem onto SkyDrive's support forum. I hope that someone might be able to propose a better solution to the problem that I have. Thanks for your help.
    MDSms asked on
    Uploaded jar files convert to jar.zip files when downloaded from SkyDrive
    I have uploaded an executable jar file to SkyDrive. (I will call this FILE.jar). The file is intact and indicates that it is a jar file type when the file is viewed by Properties within Skydrive. However, when I download (or others download through a share link) the file, it is being saved onto the local computer's download file with .zip appended to the file name (FILE.jar.zip). The downloaded file can be renamed to remove the .zip appendage and subsequently run successfully. However the folder options for the folder where the downloaded file resides must be changed for disable "Hide known file extensions" prior to being able to remove the .zip appendage. While I have figured out the workaround for this problem, this manual renaming procedure is entirely too cumbersome as a solution for sharing this file with others. How can I prevent or disable the FILE.jar file from being renamed to FILE.jar.zip when it is downloaded from SkyDrive?
    All Replies (5)
    Audrey_P. replied on
    Forum Moderator
    Hi,
    Thank you for posting. Let me try to assist you with your issue with your files.
    In order for us to reproduce the issue on our end. Please provide us with the exact steps that you did when you uploaded the files as well as the steps when you are downloading it.
    We will be needing the steps to help us figure put what is causing you this issue.
    We look forward to your response.
    Thank you.
    Audrey P.
    MDSms replied on
    Reply
    The file was uploaded by first logging onto my SkyDrive account using Windows 7 Pro and Firefox browser, then a new folder in my account was created without sharing privileges, then the folder was opened and the FILE.jar was uploaded into the folder using the "Upload" option on skydrive account menu. Sharing privileges for FILE.jar were then created (view only), and the shortened url link was sent to the individuals that I was trying to share the file with. was then turned on. When these people use the link to download the file, it is being saved as FILE.jar.zip.
    When I try to download the file through the skydrive account download option, it is being saved onto my computer as FILE.jar.zip and this occurs when I try to download the file while signed into my skydrive account as well as when I am not signed into my skydrive account (using the shared file link).
    This PNG shows the information provided by clicking on the download icon (down arrow) within the Firefox browser; note that the file was downloaded as FILE.jar.zip and that the source was live.com. When I use Windows Explorer to look at the same file within the Download folder itself, examining the file's properties details also shows that it is being saved as FILE.jar.zip and is of the file type compressed zip folder.
    This PNG shows the information displayed to me from my skydrive account when I view the originally uploaded file's properties; note that the information shows that the file is a jar file type.
    When I utilize Internet Explorer 9 to access the file, FILE.jar is being downloaded onto my computer as a jar file type. This PNG shows the information provided by Tools/View Downloads within the IE9 browser. Note that in this instance, the information indicates that the file is being downloaded from yzudea.blu.livefilestore.com.
    It appears to me that the problem (the FILE.jar file being renamed to FILE.jar.zip) arises from the fact that a jar file downloaded from skydrive using firefox, is being sent from live.com whereas a jar file downloaded from skydrive using IE9 is being sent from yzudea.blu.livefilestore.com.
    I want to make sure that a person receiving a share link from me for FILE.jar is able to download it without modification to the file name regardless of which browser is being using to access the link. How can I make sure that this occurs?
    Any help is appreciated. Thanks.
    Michelle Anne D. replied on
    Forum Moderator Community Star Community Star
    Reply
    Hi MDSms,
    I appreciate you for providing as much information as you can about the issue, as well as for uploading screenshots on what you see from the downloaded file. About your initial concern wherein the file gets renamed with .zip after the original file extension, this is solely dependent on the browser that you are using since they have a different safety/security measure that needs to be implemented.
    Moreover, you may see the file servers live.com and yzudea.blu.livefilestore.com to be different with one another, but they actually are sent from the same SkyDrive server. This in turn, depends on the web browser where the file is being downloaded as well. The live.com file where it was downloaded from Firefox simply masks its original server yzudea.blu.livefilestore.com.
    As for your last query about your recipients downloading the file without the hassle of renaming it from a .zip file, you can simply tell them to download it through Internet Explorer.
    Should you have other queries or additional information that might help in our investigation, I highly encourage you to post them here.
    Regards,
    Michelle
    MDSms replied on
    Michelle,
    Thanks for your reply. Yes, I could simply tell them to download the file through Internet Explorer, but is there another solution or workaround to the problem I have described here? Am I being punished with the curse of this problem simply because I (or the individuals with which I wish to share FILE.jar with) choose to use Firefox instead of IE? Will the use of any other browser instead of IE (Chrome, Safari, etc., etc.) still result in the same problem?
    You stated that it is "solely dependent on the browser that you are using since they have a different safety/security measure that needs to be implemented"........could the problem be overcome by designating one or both of the file server addresses as Trusted Sites within the browser options setting?
    I look forward to your response. Thanks in advance.
    Joy V. replied on
    Forum Moderator Community Star Community Star
    Reply
    Hi MDSms,
    We understand your concern. Since the issue does not occur in Internet Explorer, it has something to do with Firefox's security feature. You might want to verify this concern by contacting Firefox support.
    Hope this helps. Let us know if we can further assist you with SkyDrive.
    Thanks,
    Melanie Joy

    Try to delete the mimeTypes.rdf file in the Firefox profile folder to reset all file actions.
    *http://kb.mozillazine.org/mimeTypes.rdf
    *http://kb.mozillazine.org/File_types_and_download_actions#Resetting_download_actions

  • 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

  • Sending HR-File as email by the ABAP program as password protected ZIP file

    Hi All,
    My requiremet is to directly email the SAP-HR files to the users as the password protected ZIP file on UNIX.
    Can anyone help me out how to implement this in my ABAP program.
    Regards,
    Saumik

    hi,
    To populate data in different column you may use the below code.
    DATA : filename TYPE string VALUE  "Path
    DATA :BEGIN OF wa_string,
                   data TYPE string,
              END OF wa_string.
    DATA : it_data LIKE STANDARD TABLE OF wa_string,
               data  TYPE string.
    DATA: v_tab TYPE char1.
    v_tab = cl_abap_char_utilities=>horizontal_tab.
    CONCATENATE 'happy' 'new year'  INTO wa_string-data SEPARATED BY v_tab.
    APPEND wa_string TO it_data .
    CALL FUNCTION 'GUI_DOWNLOAD'
      EXPORTING
        filename              = filename
      TABLES
        data_tab              = it_data.
    IF sy-subrc <> 0.
    ENDIF.

  • Setting the name of streamed zip file

    Hi,
    I have a servlet which creates a zip file with documents retrieved from a database. To create the zip file I am using the ZipOutputStream class and adding the documents one at a time to this object. This is all working fine.
    The problem I have is pretty simple, in that I can't seem to find a way in which to set the name of the zip file. This must be possible! At the moment it appears to be setting the name of the zip file to the name of the class that created it. In this case my class is called DocumentPacker and what comes back from the servlet is a zip file called DocumentPacker.zip. This wouldn't be so bad, but if you're creating the zip file for a user that does not have cookies enabled, it appends the session id to the end of the zip file name which i don't want.
    I am creating my ZipOutputStream like this:
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
    and then adding the documents one at a time using a BufferedInputStream.).
    Any help on how to set the name would be much appreciated
    Thanks
    Claire

    Your servlet must set some headers on the HTTP response (Content-Type as "application/zip", Content-Disposition as "attachment; filename=yourfilename.zip")
    Read the RFC1806 document.
    Content-Type: application/zip
    Content-Disposition: attachment; filename=genome.jpeg

  • ByteArrayInputStream as source for zip file entry corrupts the ByteArray

    Hi All,
    I have managed to create and add a (in-memory) zip file as an email attachment. I add a file to the zip file , then push data to this file via a ByteArrayInputStream.
    Adding the file (created via ByteArrayInputStream) to an email works perfectly. If i then add another step and zip this file it corrupts the output.
    It looks like it is turning the carriage return into a [] . Its 'almost right' as when I cut & paste the contents of the txt file i created (from the zip file) into Word it displays correctly, with the carriage returns. Is it some kind of encoding problem, or mime type issue?
    My ByteArrayInputStream uses buf.append("\n"); for carriage returns. I think the problem is with
    ByteArrayInputStream baIn = new  ByteArrayInputStream( getAttachementNoFormat(eq_rt.getStoredProc()) );where I think i need to encode this somehow. Here is the complete code to create and add the zip file to an email. Any isuggestions will be appreciated.
    //START of new ZIP code    
                                                                                             /* Specify files to be zipped */
                                                                                            // Create temp file.
                                                                                            //File temp = File.createTempFile(fileName, ".txt");                           
                                                                                            //temp.deleteOnExit();                                                           
                                                                                            //BufferedWriter bOut = new BufferedWriter(new FileWriter(temp));                                                          
                                                                                            //ByteArrayInputStream baInTemp = new ByteArrayInputStream( getAttachementNoFormat(eq_rt.getStoredProc() ) );
                                                                                            //bOut.write( baInTemp.toString() );
                                                                                            //bOut.close();
                                                                                             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";
                                                                                             final String fileToZip = fileName;
                                                                                             /*  Create a memory buffer to store the ByteArray, fixed size */                                                         
                                                                                             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++) {
                                                                                                    /* Print the filenumber being added to the zip */
                                                                                                    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());
                                                                                                    //String strSocketInput = new String (getAttachementNoFormat(eq_rt.getStoredProc()).toString() );                                                                                           
                                                                                                    //ByteArrayInputStream baIn = new ByteArrayInputStream( getAttachementNoFormat(eq_rt.getStoredProc()) );
                                                                                                     ByteArrayInputStream baIn = new  ByteArrayInputStream( getAttachementNoFormat(eq_rt.getStoredProc()) );
                                                                                                    //String strSocketInput = "TAIWAN";
                                                                                                    //ByteArrayInputStream baIn = new ByteArrayInputStream(strSocketInput.getBytes());
                                                                                                    /* 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();                                                   
                                                                                                /* 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/gzip" );
                                                                                                /* 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);                                                       
                                                                                             catch (IllegalArgumentException iae) {
                                                                                               iae.printStackTrace();
                                                                                             catch (FileNotFoundException fnfe) {
                                                                                               fnfe.printStackTrace();
                                                                                             catch (IOException ioe)
                                                                                             ioe.printStackTrace();
                                                                                           // End Of New ZIP code    

    I came up with 'a' solution (not sure if its the best way but appears to work)
    \n = corrupt
    \r\n = ok in zip

  • Can't open the Zipped file

    Hi
    I am making a zip file using GZIPOutputStream. But I am not able to open the zip file that is created using win zip.The size of the zipped file is 81 KB and the input file is 3,245 KB.I have closed all the streams still I am not able to figure out the problem.Any idea where I am going wrong ? Any help would be greatly appreciated.
    Here my code goes:
    import java.util.zip.*;
    import java.io.*;
    public class ZipFile
         public static void main(String[] args) throws FileNotFoundException,IOException
              ZipFile("D:\\Java\\Test\\INPUTXML_bkp_1.xml");
         public static String ZipFile(String fileName) throws FileNotFoundException,IOException
              String name = fileName.substring(fileName.lastIndexOf('\\') +1 ,fileName.lastIndexOf('.'));
              String filePath = fileName.substring(0,fileName.indexOf(name));
              String newFileName = new StringBuffer(name).append(".zip").toString();
              FileOutputStream outputStream = new FileOutputStream(newFileName);
              GZIPOutputStream zipOutputStream = new GZIPOutputStream(outputStream);
              FileInputStream inputStream = new FileInputStream(fileName);
              byte[] temp = new byte[10000000];
              int counter = inputStream.read(temp,0,temp.length);
              zipOutputStream.write(temp,0,counter);
              inputStream.close();
              zipOutputStream.finish();
              zipOutputStream.close();
              return newFileName;
    Thanks
    Ritesh

    Thanks for the reply.
    I changed my code to look like this:
    import java.util.zip.*;
    import java.io.*;
    public class ZipFile
         public static void main(String[] args) throws FileNotFoundException,IOException
              ZipFile("D:\\Java\\Test\\INPUTXML_bkp_1.xml");
         public static String ZipFile(String fileName) throws FileNotFoundException,IOException
              String name = fileName.substring(fileName.lastIndexOf('\\') +1 ,fileName.lastIndexOf('.'));
              String filePath = fileName.substring(0,fileName.indexOf(name));
              String newFileName = new StringBuffer(name).append(".zip").toString();
              FileOutputStream outputStream = new FileOutputStream(newFileName);
              ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
              ZipEntry zipEntry = new ZipEntry(fileName);
              zipOutputStream.putNextEntry(zipEntry);
              zipOutputStream.finish();
              zipOutputStream.close();
              return newFileName;
    Now I can atleast open the zip file. But the problem is the size of the file is 0 kb. Probably because, I am not populating the Zip entry. Can u pls let me know how do I do that.
    Thanks
    Ritesh

  • Problem in unzipping the zip files

    Hi,
    I have created a program to unzip the zip files. But when i try to zip it is creating the zipped files outside the folder where it is to be zipped.
    what is wrong with my code.
    if the zip file is migration.zip
    if the path inside the zip file shows
    and the path inside says this
    /codebase/scripts/
    it would create migration folder and create codebase folder outside the migration folder
    what is wrong with my code
    //Unzip the zip files to the folder with their name
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.FilenameFilter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Enumeration;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    // Getting the path to find the type of files
    public class zipper implements FilenameFilter{
              String ext;
              public zipper(String ext)
                   this.ext="." + ext;
              public boolean accept(File dir,String name)
                   return name.endsWith(ext);
    public static void main(String args[]) throws IOException
              try
                        String dir = "D:/a/";
                        File f2 = new File(dir);
                        FilenameFilter fn= new zipper("zip");
                        String ss[]=f2.list(fn);
                   for ( int j = 0; j < ss.length; j++)
                        System.out.println(" Extracting ...." + ss[j]) ;
                        String zipFile = dir + ss[j];
                        ZipFile zf = new ZipFile(zipFile);
                        Enumeration entries = zf.entries();
                        String directoryName = zf.getName();
                        directoryName = directoryName.substring(0, (directoryName.indexOf(":" + File.separator) + 2));
                             String folderName = zf.getName();
                             folderName = folderName.substring(0, folderName.lastIndexOf("."));
                             File file1 = new File(folderName);
                             //File file1 = new File(entries.getName());
                             file1.mkdir();
                   while (entries.hasMoreElements())
                             ZipEntry ze = (ZipEntry) entries.nextElement();
                             String path = directoryName + ze.getName() ;
                             String path1 = folderName + ze.getName();
                             //System.out.println(" : " + path);
                             if (ze.getName().endsWith("/"))
                                       File file = new File(path);
                                       file.mkdir();
                                       continue;
                                       //break;
                        BufferedReader bReader = new BufferedReader(new InputStreamReader(zf.getInputStream(ze)));
         StringBuffer fileBuffer = new StringBuffer(" ");
         String line ;
                        while ((line = bReader.readLine()) != null)
                                  fileBuffer.append(line);
                                  fileBuffer.append("\r\n");
                                  //line = line + "\r\n";
                                  //byte[] b = new byte[line.length()];
                                  //b =line.getBytes();
                                  //out.write();
                        String fileData = fileBuffer.toString();
         File f1 = new File(path);
                        f1.createNewFile();
                        //FileOutputStream out = new FileOutputStream(folderName + "/" + ze.getName());
                        FileOutputStream out = new FileOutputStream(path);
                        long size = ze.getSize();
                        byte[] data1 = new byte[fileData.length()];
                        for (int i = 0; i < fileData.length(); i++)
                                  data1[i] = (byte) fileData.charAt(i);
         out.write(data1);
         out.close();
                        bReader.close();                         
                   } catch (Exception e)
                             e.printStackTrace();
    Thanks in Advance
    Avinash

    String path = directoryName + ze.getName();
    String path1 = folderName + File.separator+ ze.getName();
    File f1 = new File(path); // pass path1 instead of path
    f1.createNewFile();
    FileOutputStream out = new FileOutputStream(path); // pass path1 instead of path

  • Problem in Unzipping the zip file

    Hi
    I have created a program to unzip the zip files in the folder named after the zip file
    it is working well well when u try to zip zip files put in a directory
    i.e u create a folder name contents and put files into that and then zip it
    but when u directly create a zip file , without putting in a folder
    it creates the folder and zip the files outside the folder
    Another problem is that with the path
    for e.g. suppose the zip file name is contents and path should show
    contents/filename.txt but there are some other files whose path shows
    res/file.txt. In this case it creates a folder of res and put it outside the
    folder with the name of zip file
    I have pasted my code :
    //Unzip the zip files to the folder with their name
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.FilenameFilter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Enumeration;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    // Getting the path to find the type of files
    public class zipper implements FilenameFilter{
              String ext;
              public zipper(String ext)
                   this.ext="." + ext;
              public boolean accept(File dir,String name)
                   return name.endsWith(ext);
    public static void main(String args[]) throws IOException
              try
                        String dir = "D:/";
                        File f2 = new File(dir);
                        FilenameFilter fn= new zipper("zip");
                        String ss[]=f2.list(fn);
                   for ( int j = 0; j < ss.length; j++)
                        System.out.println(" Extracting ...." + ss[j]) ;
                        String zipFile = dir + ss[j];
                        ZipFile zf = new ZipFile(zipFile);
                        Enumeration entries = zf.entries();
                        String directoryName = zf.getName();
                        directoryName = directoryName.substring(0, (directoryName.indexOf(":" + File.separator) + 2));
                             String folderName = zf.getName();
                             folderName = folderName.substring(0, folderName.lastIndexOf("."));
                             File file1 = new File(folderName);
                             //File file1 = new File(entries.getName());
                             file1.mkdir();
                   while (entries.hasMoreElements())
                             ZipEntry ze = (ZipEntry) entries.nextElement();
                             String path = directoryName + ze.getName() ;
                             String path1 = folderName + ze.getName();
                             //System.out.println(" : " + path);
                             if (ze.getName().endsWith("/"))
                                       File file = new File(path);
                                       file.mkdir();
                                       continue;
                                       //break;
                        BufferedReader bReader = new BufferedReader(new InputStreamReader(zf.getInputStream(ze)));
         StringBuffer fileBuffer = new StringBuffer(" ");
         String line ;
                        while ((line = bReader.readLine()) != null)
                                  fileBuffer.append(line);
                                  fileBuffer.append("\r\n");
                                  //line = line + "\r\n";
                                  //byte[] b = new byte[line.length()];
                                  //b =line.getBytes();
                                  //out.write();
                        String fileData = fileBuffer.toString();
         File f1 = new File(path);
                        f1.createNewFile();
                        //FileOutputStream out = new FileOutputStream(folderName + "/" + ze.getName());
                        FileOutputStream out = new FileOutputStream(path);
                        long size = ze.getSize();
                        byte[] data1 = new byte[fileData.length()];
                        for (int i = 0; i < fileData.length(); i++)
                                  data1[i] = (byte) fileData.charAt(i);
         out.write(data1);
         out.close();
                        bReader.close();                         
                   } catch (Exception e)
                             e.printStackTrace();
    Thanks in Advance
    Avinash

    String path = directoryName + ze.getName();
    String path1 = folderName + File.separator+ ze.getName();
    File f1 = new File(path); // pass path1 instead of path
    f1.createNewFile();
    FileOutputStream out = new FileOutputStream(path); // pass path1 instead of path

  • Sending zip file(or folder ) from desktop to email attachment

    Dear all
    I hvae 11 files on my desktop of differnt file type like doc, pdf, xls ...
    By using GUI_UPLOAD, i am able to upload one file at a time
    Is there any way to upload zip file at once OR folder containing all the files at a single go  OR all the files can be uploaded in a single program.
    Is there any class, function module to upload zip file. I am aware of cl_abap_zip but not able to use it.
    Ravi
    Edited by: ravihsr on Mar 24, 2011 3:05 AM
    Edited by: ravihsr on Mar 24, 2011 3:14 AM

    Hi
    This the code:
    REPORT  Z263_EMAIL.
    data: T_MAIL_PACK TYPE TABLE OF SOPCKLSTI1,
          T_MAIL_HEAD TYPE TABLE OF SOLISTI1,
          T_MAIL_REC TYPE TABLE OF SOMLRECI1,
          MAIL_HEAD TYPE SODOCCHGI1,
          T_MAILTXT TYPE TABLE OF SOLISTI1,
          WA_MAIL_PACK TYPE SOPCKLSTI1,
          WA_MAIL_HEAD TYPE SOLISTI1,
          WA_MAIL_REC TYPE  SOMLRECI1,
          WA_MAILTXT TYPE SOLISTI1,
          TAB_LINES TYPE I.
    *FILLING HEADER
    MAIL_HEAD-OBJ_NAME  = 'NEW MAIL TO BE SENT'.
    MAIL_HEAD-OBJ_DESCR = 'SUBJECT FOR MAIL'.
    WA_MAILTXT-LINE = 'MAIL OUTPUT'.
    APPEND WA_MAILTXT TO T_MAILTXT.
    WA_MAIL_REC-RECEIVER = '******@****.COM'. "email-id
    WA_MAIL_REC-REC_TYPE = 'U'.
    APPEND WA_MAIL_REC TO T_MAIL_REC.
    DESCRIBE TABLE T_MAILTXT LINES TAB_LINES.
    CLEAR WA_MAIL_PACK-TRANSF_BIN.
    WA_MAIL_PACK-HEAD_START = 1.
    WA_MAIL_PACK-HEAD_NUM = 0.
    WA_MAIL_PACK-BODY_START = 1.
    WA_MAIL_PACK-BODY_NUM = TAB_LINES.
    WA_MAIL_PACK-DOC_TYPE = 'RAW'.
    WA_MAIL_PACK-OBJ_NAME = 'C:\Documents and Settings\rmalhotra\Desktop\NEW.RAR'.
    APPEND WA_MAIL_PACK TO T_MAIL_PACK.
    WA_MAIL_PACK-TRANSF_BIN = 'X'.
    WA_MAIL_PACK-HEAD_START = 1.
    WA_MAIL_PACK-HEAD_NUM = 1.
    WA_MAIL_PACK-BODY_START = 1.
    WA_MAIL_PACK-BODY_NUM = TAB_LINES.
    WA_MAIL_PACK-DOC_TYPE = 'XLS'.
    WA_MAIL_PACK-OBJ_NAME = 'C:\Documents and Settings\rmalhotra\Desktop\a1.xls'.
    WA_MAIL_PACK-OBJ_DESCR = 'ORDERS'.
    *WA_MAIL_PACK-DOC_SIZE = TAB_LINES * 128.
    APPEND WA_MAIL_PACK TO T_MAIL_PACK.
    DESCRIBE TABLE gv_objbin LINES tab_lines.
    WA_MAIL_PACK-transf_bin = 'X'.
    WA_MAIL_PACK-head_start = 1.
    WA_MAIL_PACK-head_num = 1.
    WA_MAIL_PACK-body_start = 1.
    WA_MAIL_PACK-body_num = tab_lines.
    WA_MAIL_PACK-doc_type = 'PDF'.
    WA_MAIL_PACK-obj_name = 'C:\Documents and Settings\rmalhotra\Desktop\RAGHAV_SMARTFORM.pdf'.
    *WA_MAIL_PACK-doc_size = tab_lines * 255.
    APPEND WA_MAIL_PACK TO T_MAIL_PACK.
    WA_MAIL_PACK-transf_bin = 'X'.
    WA_MAIL_PACK-head_start = 1.
    WA_MAIL_PACK-head_num = 1.
    WA_MAIL_PACK-body_start = 1.
    WA_MAIL_PACK-body_num = tab_lines.
    WA_MAIL_PACK-doc_type = 'TXT'.
    WA_MAIL_PACK-obj_name = 'C:\Documents and Settings\rmalhotra\Desktop\VOTES.TXT'.
    *WA_MAIL_PACK-doc_size = tab_lines * 255.
    APPEND WA_MAIL_PACK TO T_MAIL_PACK.
    WA_MAIL_PACK-transf_bin = 'X'.
    WA_MAIL_PACK-head_start = 1.
    WA_MAIL_PACK-head_num = 1.
    WA_MAIL_PACK-body_start = 1.
    WA_MAIL_PACK-body_num = tab_lines.
    WA_MAIL_PACK-doc_type = 'DOC'.
    WA_MAIL_PACK-obj_name = 'C:\Documents and Settings\rmalhotra\Desktop\TS-MRO-47- Warranty Claim Creation v1.0.doc'.
    *WA_MAIL_PACK-doc_size = tab_lines * 255.
    APPEND WA_MAIL_PACK TO T_MAIL_PACK.
    CALL FUNCTION 'SO_NEW_DOCUMENT_ATT_SEND_API1'
      EXPORTING
        DOCUMENT_DATA                    = MAIL_HEAD
      PUT_IN_OUTBOX                    = ' '
       COMMIT_WORK                      = 'X'
    IMPORTING
      SENT_TO_ALL                      =
      NEW_OBJECT_ID                    =
      TABLES
        PACKING_LIST                     = T_MAIL_PACK
      OBJECT_HEADER                    =
      CONTENTS_BIN                     =
       CONTENTS_TXT                     = T_MAILTXT
      CONTENTS_HEX                     =
      OBJECT_PARA                      =
      OBJECT_PARB                      =
        RECEIVERS                        = T_MAIL_REC
    EXCEPTIONS
       TOO_MANY_RECEIVERS               = 1
       DOCUMENT_NOT_SENT                = 2
       DOCUMENT_TYPE_NOT_EXIST          = 3
       OPERATION_NO_AUTHORIZATION       = 4
       PARAMETER_ERROR                  = 5
       X_ERROR                          = 6
       ENQUEUE_ERROR                    = 7
       OTHERS                           = 8
    IF SY-SUBRC <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
             WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    SUBMIT RSCONN01.
    Regards
    Raghav Malhotra

  • Append an existing file?

    Hello world,
    I'm stuck in a predicament: The storage guys have asked me to reduce the frequency of backups on three of our instances to save bandwidth on the WAN when the backup files are copied across to another datacenter. The application owners do not want to backup
    any less frequently. 
    We do daily full backups and Tr-log backups every 15 minutes throughout the day.
    Storage have advised that the SAN only copies changes (ie new files or the changes to existing ones)
    Is it possible/ would it be of any benefit, to backup and append an existing file? Can I do this with the logs as with the databases?
    Thanks in advance

    Storage have advised that the SAN only copies changes (ie new files or the changes to existing ones)
    I am not very sure that it will pick changes from existing ones, I think if it sees the file is changed it will start coping as 1 big file and will not solve your purpose. You might get it reconfirm with storage on this. Also even if it does like you said
    I wonder if next backup runs and file is still getting copied over then backup will start failing saying "file is in use".
    If application owner is saying 15 min log backup then we cant reduce the frequency, but if you have some other drive/disk where you can divert tlog backup say for 2 hours then you can run differential backup every 2 hour which goes to SAN. You will be safe
    even if something happen you have tlog on 1 drive and
    differential get copied to other datacenter. (But point in time recovery will be issue as you will not have any tlog backups for restore)
    I cant think of anything else to reduce frequency, but for bandwidth see if you can use compress(enterprise edition) or zip backup file to save bandwidth.

  • Zip: concatening compressed chunks, will it give a single zip file

    Are concatenated zipped chunks recognized as a single zip file?
    What I am trying to achieve(using java.util.zip) is like, my application is generating a large CSV file, i need to compress this data and write it into a file or send to network. But I dont want to wait until the complete data generation and need to compress data in chunks; assuming that if i append my compressed chunks to a file at last i will get a valid & complete zip file.
    For testing this I made a sample program like:
    //Here a.zip b.zip are files compressed using java.util.zip; here they act as
    // data chunk (actually these will be genarted by my
    // application dynamically & in parallel to this process)
    FileInputStream f1 = new FileInputStream(new File("c://a.zip"));
    FileInputStream f2 = new FileInputStream(new File("c://b.zip"));
    // Opening file in append mode
    FileOutputStream fos = new FileOutputStream("c://c.zip",true);
    byte[] data = new byte[(int)new File("c://a.zip").length()];
    f1.read(data);
    fos.write(data);
    byte[] data2 = new byte[(int)new File("c://b.zip").length()];
    f2.read(data2);
    fos.write(data2);
    f1.close();
    f2.close();
    fos.close();
    But this program does not work, as m not getting the final zip file containing the whole data, rather it gives data only from first file.
    Can any one point out the error.
    Or suggest me the better way to achieve this.

    hi
    i want to sugest you like:--
    say fileoutputstreem.flesh();
    call this flesh() method . It is just like commit in DB.
    Through this U may salve your problem.
    You are creating zip files like a.zip and b.zip if you save in your c:\\ it will take some IO Operations. It is not sugested.
    If you want to like that only i will sujest you to delete them after your process is completed.

Maybe you are looking for

  • Need to convert the binary data in blob field to readable format

    Hi, We need to convert the Binary data in the BLOB field to readable format and need to display it in Oracle Apps Environment,does anybody come across the similar requirement. please advise, thanks in advance. Regards, Babu.

  • How to get Vendor Text in BBP_POC in SRM for Smartforms?

    Hi Guys, I kept looking for ways on how to get the Vendor Text in BBP_POC transaction to be used in our Zsmartforms; unfortunately, I was not able to identify how. In ECC system, I could get the long text through double-clicking on the text area and

  • OAS 10.1.1 in Red Hat 5

    Hello, I find a manual for OAS 10.1.3 on Red Hat 5. Thanks for your answers

  • Clearing for customers

    Hi we are working on automatic customer clearance but facing some difficulties. In OB74 what criteria i should define for clearing customers automatically. I have tried using Assignment number but that doesnot work for me. please guide.

  • Summary - please help me!

    Hello everyone Please help me. I am designing a project cost report in Crystal Report. the following details will be on my report. item Code, Description, Projected Cost, Total Purchase, Left to complete. Let me give you brief detail about my tables.