How do I compress a string with  java.util.zip - not a file ?

How do I compress a string with java.util.zip?
Is possible to compress something else except a file?

Of course, compression works on bytes, not some higher level constructs like Strings or files.
You can use the ZipOutputStream or DeflaterOutputStream for compression.
And the javadoc for Deflater even has a code example of compressing a String.
Edited by: Kayaman on May 22, 2011 5:04 PM

Similar Messages

  • How to zip one file i have on disk with java.util.zip

    I don't know how to zip a file. I managed to do new html file, but i don't know how to zip it.
    This is my code:
    PrintWriter pw = new PrintWriter (new FileWriter(export), true);
    Thanks!

    heres a zipper class i wrote which i have butchered a bit to make more generic (its basic and at present only takes one zipentry etc, but very simple and should be easy to extend etc) Just pass it your file in its constructor and then call its zipme method. PS if it can be made better let me know so i can update my class, cheers.
    import java.io.*;
    import java.util.zip.*;
    import java.awt.*;
    class zipper
         public File file;
         public zipper(File f)
              file = new File(f);
         public void zipme()
              try
                   FileInputStream fin = new FileInputStream(file);
                   int a = (int)file.length();
                   byte b[] = new byte[a];
                   fin.read(b);
                   ZipEntry k = new ZipEntry(fin.getName());//represents a single file in a zip archive!
                   File newFile = new File("D:\\AZipFile.zip");
                   ZipOutputStream zi = new ZipOutputStream(new FileOutputStream(newFile));
                   zi.putNextEntry(k);
                   zi.write(b,0,a);
                   zi.close();
                   fin.close();
              catch(FileNotFoundException e)
                   //System.out.println("ERROR File not found");
              catch(IOException ee)
                   //System.out.println("ERROR IO exception in Zipping file");
    }

  • Cannot extract Zip file with Winzip after zipping with java.util.zip

    Hi all,
    I write a class for zip and unzip the text files together which can be zip and unzip successfully with Java platform. However, I cannot extract the zip file with Winzip or even WinRAR after zipping with Java platform.
    Please help to comment, thanks~
    Below is the code:
    =====================================================================
    package myapp.util;
    import java.io.* ;
    import java.util.TreeMap ;
    import java.util.zip.* ;
    import myapp.exception.UserException ;
    public class CompressionUtil {
      public CompressionUtil() {
        super() ;
      public void createZip(String zipName, String fileName)
          throws ZipException, FileNotFoundException, IOException, UserException {
        FileOutputStream fos = null ;
        BufferedOutputStream bos = null ;
        ZipOutputStream zos = null ;
        File file = null ;
        try {
          file = new File(zipName) ; //new zip file
          if (file.isDirectory()) //check if it is a directory
         throw new UserException("Invalid zip file ["+zipName+"]") ;
          if (file.exists() && !file.canWrite()) //check if it is readonly
         throw new UserException("Zip file is ReadOnly ["+zipName+"]") ;
          if (file.exists()) //overwrite the existing file
         file.delete();
          file.createNewFile();
          //instantiate the ZipOutputStream
          fos = new FileOutputStream(file) ;
          bos = new BufferedOutputStream(fos) ;
          zos = new ZipOutputStream(bos) ;
          this.writeZipFileEntry(zos, fileName); //call to write the file into the zip
          zos.finish() ;
        catch (ZipException ze) {
          throw ze ;
        catch (FileNotFoundException fnfe) {
          throw fnfe ;
        catch (IOException ioe) {
          throw ioe ;
        catch (UserException ue) {
          throw ue ;
        finally {
          //close all the stream and file
          if (fos != null)
         fos.close() ;
          if (bos != null)
         bos.close();
          if (zos != null)
         zos.close();
          if (file != null)
         file = null ;
        }//end of try-catch-finally
      private void writeZipFileEntry(ZipOutputStream zos, String fileName)
          throws ZipException, FileNotFoundException, IOException, UserException {
        BufferedInputStream bis = null ;
        File file = null ;
        ZipEntry zentry = null ;
        byte[] bArray = null ;
        try {
          file = new File(fileName) ; //instantiate the file
          if (!file.exists()) //check if the file is not exist
         throw new UserException("No such file ["+fileName+"]") ;
          if (file.isDirectory()) //check if the file is a directory
         throw new UserException("Invalid file ["+fileName+"]") ;
          //instantiate the BufferedInputStream
          bis = new BufferedInputStream(new FileInputStream(file)) ;
          //Get the content of the file and put into the byte[]
          int size = (int) file.length();
          if (size == -1)
         throw new UserException("Cannot determine the file size [" +fileName + "]");
          bArray = new byte[(int) size];
          int rb = 0;
          int chunk = 0;
          while (((int) size - rb) > 0) {
         chunk = bis.read(bArray, rb, (int) size - rb);
         if (chunk == -1)
           break;
         rb += chunk;
          }//end of while (((int)size - rb) > 0)
          //instantiate the CRC32
          CRC32 crc = new CRC32() ;
          crc.update(bArray, 0, size);
          //instantiate the ZipEntry
          zentry = new ZipEntry(fileName) ;
          zentry.setMethod(ZipEntry.STORED) ;
          zentry.setSize(size);
          zentry.setCrc(crc.getValue());
          //write all the info to the ZipOutputStream
          zos.putNextEntry(zentry);
          zos.write(bArray, 0, size);
          zos.closeEntry();
        catch (ZipException ze) {
          throw ze ;
        catch (FileNotFoundException fnfe) {
          throw fnfe ;
        catch (IOException ioe) {
          throw ioe ;
        catch (UserException ue) {
          throw ue ;
        finally {
          //close all the stream and file
          if (bis != null)
         bis.close();
          if (file != null)
         file = null ;
        }//end of try-catch-finally
    }

    Tried~
    The problem is still here~ >___<
    Anyway, thanks for information sharing~
    The message is:
    Cannot open file: it does not appear to be a valid archive.
    If you downloaded this file, try downloading the file again.
    The problem may be here:
    if (fos != null)
    fos.close() ;
    if (bos != null)
    bos.close();
    if (zos != null)
    zos.close();
    if (file != null)
    file = null ;
    The fos is closed before bos so the last buffer is not
    saved.
    zos.close() is enough.

  • Extracting file from a TAR file with java.util.zip.* classes

    Is there a way to extract files from a .TAR file using the java.util.zip.* classes?
    I tried in some ways but I get the following error:
    java.util.zip.ZipException: error in opening zip file
    at java.util.zip.ZipFile.<init>(ZipFile.java127)
    at java.util.zip.ZipFile.<init>(ZipFile.java92)
    Thank you
    Giuseppe

    download the tar.jar from the above link and use the sample program below
    import com.ice.tar.*;
    import java.util.zip.GZIPInputStream;
    import java.io.*;
    public class untarFiles
         public static void main(String args[]){
              try{
              untar("c:/split/20040826172459.tar.gz",new File("c:/split/"));
              }catch(Exception e){
                   e.printStackTrace();
                   System.out.println(e.getMessage());
         private static void untar(String tarFileName, File dest)throws IOException{
              //assuming the file you pass in is not a dir
              dest.mkdir();     
              //create tar input stream from a .tar.gz file
              TarInputStream tin = new TarInputStream( new GZIPInputStream( new FileInputStream(new File(tarFileName))));
              //get the first entry in the archive
              TarEntry tarEntry = tin.getNextEntry();
              while (tarEntry != null){//create a file with the same name as the tarEntry  
                   File destPath = new File(
                   dest.toString() + File.separatorChar + tarEntry.getName());
                   if(tarEntry.isDirectory()){   
                        destPath.mkdir();
                   }else {          
                        FileOutputStream fout = new FileOutputStream(destPath);
                        tin.copyEntryContents(fout);
                        fout.close();
                   tarEntry = tin.getNextEntry();
              tin.close();
    }

  • Problems with java.util.zip

    I've got a odd problem here. I'm not sure if this is the appropriate forum but I couldn't find anyplace more appropriate.
    So the problem is...
    I create my ZIP file and if I open it in WinZip, no problem. But if I open the ZIP file using the 'Compressed Folders' feature of Windows Explorer I don't see any of the files. As far as I can tell, if the files I ZIP up do not contain any path information then they open fine via 'Compressed Folders'.
    Is this a bug in java.util.zip? Or is the 'Compressed Folders' feature in Windows Explorer half-baked?
    And finally is there any way for me to not include the path information of the files added to ZIP?
    Thanks.

    Looce:
    I'm more than willing to modify things.
    But I'm still curious why WinZip and Windows are treating the ZIP files differently.
    Also, the only way I can figure to get the files into the ZIP without the path information being stored in the ZIP file is by copying the files to the directory containing my application jar file and then passing in the file name without the path being specified. That is the only way FileInputStream would be able to find the files without including path information. This seems like a lot of unnecessary overhead.
    Another oddity is that if I create the ZIP archive using the file path for the FileInputStream and view the ZIP file using a HEX editor the entire path is being stored including the drive letter. But if you view the file using WinZip the path field seems to be removing the drive letter and only displaying the path. On top of that, even though the drive letter is contained in the archive if you unzip the file using WinZip it ignores the drive letter and unzips the file to whatever drive the archive is located on. In the grand scheme of things it makes sense for WinZip to ignore the drive letter.
    Thanks for you help anyways.

  • Java.util.zip not handling Unicode filenames

    I have a zip file that contains files with Asian filenames. java.util.zip.ZipFile opens it, but the filenames are garbled. Is there any way to handle filenames that contain unicode characters?

    Of course, compression works on bytes, not some higher level constructs like Strings or files.
    You can use the ZipOutputStream or DeflaterOutputStream for compression.
    And the javadoc for Deflater even has a code example of compressing a String.
    Edited by: Kayaman on May 22, 2011 5:04 PM

  • How to repeatedly replace different strings with most chars are Not unique?

    NOTE: I'm trying to avoid to do a substring of a substring of a ... replacement.
    Hello there,
    I'm looking for solution on a best approach to do a string replacment in something like example below.
    The idea would be to:
    1. Open a file and Find a "Title" (i.e. TC162-01.2GFC (after <td colspan=6>)). The Title here will be a dynamic and can be changed from one run to another.
    2. If it match to expected value then do a replacement of data between <select... and </select> for another values.
    3. Keep going for each block of <tr> ... </tr>
    =======================================
    <tr>
    <td colspan=1>1</td>
    <td colspan=1>TC1.1</td>
    <td colspan=6>TC162-01.2GFC</td>
    <td colspan=2>Unknown</td>
    <td colspan=1><select name="res_1_0_20789_21522" size=1>
    <option>PASS</option><option>FAIL</option><option selected>No Status</option></select> </td>
    <td colspan=1><input type=text maxlength='30' size='10' name='comment_1' value=''></td></tr>
    <tr>
    <td colspan=1>2</td>
    <td colspan=1>TC1.2</td>
    <td colspan=6>TC162-01.3ABC</td>
    <td colspan=2>Unknown</td>
    <td colspan=1><select name="res_2_0_20790_21523" size=1>
    <option selected>PASS</option><option>FAIL</option><option>No Status</option></select> </td>
    <td colspan=1><input type=text maxlength='30' size='10' name='comment_2' value=''></td></tr>
    =======================================

    Here's a simple and conceptual example. You could use your real implementation of the getReplace() method.
    /** file: test-vlad.txt *************************************
    <tr>
    <td colspan=1>1</td>
    <td colspan=1>TC1.1</td>
    <td colspan=6>TC162-01.2GFC</td>
    <td colspan=2>Unknown</td>
    <td colspan=1><select name="res_1_0_20789_21522" size=1>
    <option>PASS</option><option>FAIL</option><option selected>No Status</option></select> </td>
    <td colspan=1><input type=text maxlength='30' size='10' name='comment_1' value=''></td></tr>
    <tr>
    <td colspan=1>2</td>
    <td colspan=1>TC1.2</td>
    <td colspan=6>TC162-01.3ABC</td>
    <td colspan=2>Unknown</td>
    <td colspan=1><select name="res_2_0_20790_21523" size=1>
    <option selected>PASS</option><option>FAIL</option><option>No Status</option></select> </td>
    <td colspan=1><input type=text maxlength='30' size='10' name='comment_2' value=''></td></tr>
    import java.util.regex.*;
    import java.io.*;
    public class Vlad{
      public static void main(String[] args) throws Exception{
        BufferedReader br;
        StringBuffer sb;
        String line, fcontent;
        sb = new StringBuffer();
        br = new BufferedReader(new FileReader("test-vlad.txt"));
        while ((line = br.readLine()) != null){
          sb.append(line + "\n");
        fcontent = sb.toString();
        String regex
         = "<td colspan=6>([^<]+)(</td>.+?<select[^>]+>)(.+?)</select>";
        Pattern pat = Pattern.compile(regex, Pattern.DOTALL);
        Matcher mat = pat.matcher(fcontent);
        StringBuffer rsb = new StringBuffer();
        while (mat.find()){
          String title = mat.group(1);
          String value = mat.group(3);
          String newValue = getReplace(title, value);
          mat.appendReplacement
            (rsb, "<td colspan=6>" + title + "$2" + newValue + "</select>");
        mat.appendTail(rsb);
        System.out.println(rsb.toString());
      } // end main()
      // a dummy implementation
      static String getReplace(String tdTitle, String selectValue){
        return "###ANOTHER VALUES###";
    }Edited by: hiwa on Dec 11, 2007 11:14 AM

  • Java.util.zip.ZipFile.entries() shows only 99 files but zip file is fine.

    Hi,
    I have a wierd issue with java.util.zip.ZipFile
    Code as simple as
    ZipFile file = new ZipFile("my.zip") ;
    System.out.println(file.size());
    For this particular zip file, it says 99 files found but the zip contains more than 60,000 files. I tried the zip with unzip and zip utilities and the zip file checks out fine. I even tried to unzip the contents, and zip 'em up all over again, just to eliminate the chances of corruption while the zip was being transferred over the network.
    The same program works fine with another zip containing more or less the same number of files and prints 63730.
    Any idea? This can not possibly be related to the type of files the zips contain? right? In any case, the contents of both zips are text/xml files.
    Any help would be greatly appreciated.
    Regards,
    ZiroFrequency

    I know its a problem with this particular zip. But whats interesting is that "unzip" can easily open / verify the zip and claims that it is a valid zip.
    As I wrote earlier, I unzipped the file and zipped up the contents again in a new zip but java can't still count the contents correctly.
    So I am thinking there is something to do with the "contents" of the xmls inside the zip? (characterset issues?)
    There are no exceptions thrown and no error anywhere :(
    I basically need to pinpoint the issue so that I can have it corrected upstream as this zip file processing is an ongoing process and I need to resolve it not just once but for the periodic executions.
    Hope this helps explain the issue.

  • How do I decompress a string in java?

    The string is compressed with zip and is encoded base64.
    I decocoded the string, I copied the string to a zip file and I tryed to decompress using the sample script(class UnZip2) from here: http://java.sun.com/developer/technicalArticles/Programming/compression/.
    The error is
    java.util.zip.ZipException: error in opening zip file
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.<init>(Unknown Source)
    at java.util.zip.ZipFile.<init>(Unknown Source)
    at UnZip2.main(UnZip2.java:12)
    Decompression works with other archives.
    I know the string is ok because the server where I send it makes a succesful decompression.

    user10878887 wrote:
    The string is compressed with zip and is encoded base64.
    I decocoded the string, I copied the string to a zip file Expanding on the other reply...
    It is likely that the problem is that the contents of the file incorrect.
    Your statement suggests that you wrote the base64 string to the file. That would be wrong.
    You needed to decode from base64 and then write the bytes to the file.

  • How to use a progress bar with java mail?

    Hi, i'm new here.
    I want if someone can recommend me how to show a progress bar with java mail.
    Because, i send a message but the screen freeze, and the progress bar never appear, after the send progress finish.
    Thanks

    So why would the code we post be any different than the code in the tutorial? Why do you think our code would be easier to understand? The tutorial contains explanations about the code.
    Did you download the code and execute it? Did it work? Then customize the code to suit your situation. We can't give you the code because we don't know exactly what you are attempting to do. We don't know how you have changed to demo code so that it no longer works. Its up to you to compare your code with the demo code to see what the difference is.

  • How do I compress a pdf with Create PDF so that I can attach it to e-mail?

    How do I compress a pdf with Create PDR so that I can attach it to e-mail?

    Hi, Blue Mamba.
    Your file is automatically compressed when using the CreatePDF service to convert from some other file type (e.g. Word, Excel) to PDF. For example, most PowerPoint files get compressed 50% to 90% over their original size.
    If there is a particular file you're converting to PDF using the CreatePDF service, and you are not seeing the size savings that you would like, please provide more details.
    Thanks.
    Dave

  • How to create dynamic connection string with variables using ssis.

    Hello,
    Can anyone let me know on how to create dynamic connection string with variables using ssis?
    Any help would be appreciated.

    Hi vinay9738,
    According to your description, you want to connect multiple database from multiple servers using dynamic connection.
    If in this case, we can create a Table in our local database (whatever DB we want) and load all the connection strings.  We can use Execute SQL Task to query all the connection strings and store the result-set in a variable of object type in SSIS package.
    Then use ForEach Loop container to shred the content of the object variable and iterate through each of the connection strings. And then Place an Execute SQL task inside ForEach Loop container with the SQL statements we have to run in all the DB instances. 
    For more details, please refer to the following blog:
    http://sql-developers.blogspot.kr/2010/07/dynamic-database-connection-using-ssis.html
    If there are any other questions, please feel free to let me know.
    Regards,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • How do I estimate time takes to Zip/Unzip using java.util.zip ?

    If I am compressing files or uncompressing zips using java.util.zip is there a way for me to tell the user how long it should take or for perhaps displaying a progress monitor ?

    For unzip use the ZipInputStream and pass it a CountingInputStream that keeps track ofr the number of bytes read from it (you write this). This CountingInputStream extends fileInputStream and as such can provide you with information about the total number of bytes available to be read and the number already read. This can give a crude idea of how much work has been done and how much work still needs to be done. It is inaccurate but should be good enoough for a progress bar
    As for zipping use the ZipOutputStream and pass it blocks of information. Keep track of the number of blocks you have written and the number you still need to write.
    matfud

  • Can't create log file with java.util.logging

    Hi,
    I have created a class to create a log file with java.util.logging
    This class works correctly as standalone (without jdev/weblogic)
    import java.io.IOException;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.logging.*;
    public class LogDemo
         private static final Logger logger = Logger.getLogger( "Logging" );
         public static void main( String[] args ) throws IOException
             Date date = new Date();
             DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
             String dateStr = dateFormat.format(date);
             String logFileName = dateStr + "SEC" + ".log";
             Handler fh;          
             try
               fh = new FileHandler(logFileName);
               //fh.setFormatter(new XMLFormatter());
               fh.setFormatter(new SimpleFormatter());
               logger.addHandler(fh);
               logger.setLevel(Level.ALL);
               logger.log(Level.INFO, "Initialization log");
               // force a bug
               ((Object)null).toString();
             catch (IOException e)
                  logger.log( Level.WARNING, e.getMessage(), e );
             catch (Exception e)
                  logger.log( Level.WARNING, "Exception", e);
    }But when I use this class...
    import java.io.File;
    import java.io.IOException;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.logging.FileHandler;
    import java.util.logging.Handler;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import java.util.logging.XMLFormatter;
    public class TraceUtils
      public static Logger logger = Logger.getLogger("log");
      public static void initLogger(String ApplicationName) {
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = dateFormat.format(date);
        String logFileName = dateStr + ApplicationName + ".log";
        Handler fh;
        try
          fh = new FileHandler(logFileName);
          fh.setFormatter(new XMLFormatter());
          logger.addHandler(fh);
          logger.setLevel(Level.ALL);
          logger.log(Level.INFO, "Initialization log");
        catch (IOException e)
          System.out.println(e.getMessage());
    }and I call it in a backingBean, I have the message in console but the log file is not created.
    TraceUtils.initLogger("SEC");why?
    Thanks for your help.

    I have uncommented this line in logging.properties and it works.
    # To also add the FileHandler, use the following line instead.
    handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandlerBut I have another problem:
    jdev ignore the parameters of the FileHandler method .
    And it creates a general log file with anothers log files created each time I call the method logp.
    So I play with these parameters
    fh = new FileHandler(logFileName,true);
    fh = new FileHandler(logFileName,0,1,true);
    fh = new FileHandler(logFileName,10000000,1,true);without succes.
    I want only one log file, how to do that?

  • Java.util.zip: how to save file type

    HI,
    I have a written a program that zips PDF files and sends them as an attachment via email. This have been running daily for the last 1.5 years with no problems. Recently, some email providers have been striping the attachments or refusing the email, because I have used two file suffix on the attachment, e.g report.pdf.zip. I did this so that when the file is unzipped the .pdf extension remains and file is recognised, otherwise the document is treated as plain text or unknown format. How can I include the filetype in the zipped file, so that I can have report.pdf become report.zip, then when the user unzips the file has report.zip become report.pdf. I know the filetype is stored in the zip header, but I don't know how to do this using java.util.zip. Any help would be appreciated.
    Mike

    You see, zip files are inherently dumb. They don't "actually" have a file system in the strictest sense. The zip file format merely associates a String ID with some bytes. It's all on the client side where the magic happens. if I have three zip entries in a file, these are the entry names.
    1.) somedir/myfile.txt
    2.) someotherdir/myfile.txt
    3.) README
    when a client "unzipper" see these names, it realizes that "/" is a directory separator, so it makes the appropriate directories and places the bytes into files of that given name.
    So all you should have to do is make the zip entry with a name that ends in .pdf The client should do the rest.

Maybe you are looking for

  • Approval status of PR is in process, but action history show 'Approve'

    Dear all, I am on EBS 11.5.10.2 and encountered a problem during the approval process of PR. The approval hierarchy with PR is planner -> approver1 -> approver2, and approver2 is the final approver. Everything of the approval process is OK except tha

  • How do I share data from one spreadsheet into another spreadsheet that is a separate file?

    I am trying to create a spreadsheet that will pull data from another spreadsheet in a different file for a what if scenario.  Is there a way I can reference a cell from that file besides adding a separate tab in the original file?

  • CC&B Dev Environment Installation

    Hi, Since from one week I try to setup the Dev Environment Installation for CC&B(ORMB) , however facing below error while running the cmd D:\spl\pulsev23\bin>splenviron.cmd -e pulsev23 The system cannot find the path specified. Version ..............

  • Ingesting Offline Media

    Basically, I'd really like to ingest media from tape of any size (1080p 23.98, 720p 23.98, 1080i 59.94, NTSC, etc) having it captured to OfflineRT (or some 35% quality Photo JPEG) immediately (no transcoding after capture) edit with it, and online mu

  • Somewhat large binary file has trouble being opened

    Hi, I'm a new Labview user (Labview 8.0), and I'm trying to convert a binary file into a wave file and do a lot of other things with that binary file (like analyzing frequency via a spectrum graph). My file works fine for files under 150MB, but once