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();
}

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");
    }

  • 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

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

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

  • Help with java.util.Random

    Problem:
    I wanna generate random number in interval <0;1> with two "decimal number precision" (i dont know, how to expres it exactly in English.. So, here is Patern: "*X.XX*" (For ex. it might be numbers like 0.24 , 1.00 , 0.05, 0.54) ).
    I have tried to work with java.util.Random class, but i dont understood it at all, because i'm not good in Math-English terms.
    So, how can I do it? I offer duke stars for any solve. Thanks.

    First of all, read this link to understand why all floating point numbers (float, double) can't be rounded to two places of decimals.
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic|http://docs.sun.com/source/806-3568/ncg_goldberg.html]
    Consider changing your program to use integer numbers in the range of [0..100] instead. You can generate a random number in this range byRandom random = new Random();
    int randomInt = random.nextInt(101);If your problem can't be solved with this approach, you may need to tell us exactly how you plan to further process the random number.
    luck, db

  • How to extract text from a PDF file?

    Hello Suners,
    i need to know how to extract text from a pdf file?
    does anyone know what is the character encoding in pdf file, when i use an input stream to read the file it gives encrypted characters not the original text in the file.
    is there any procedures i should do while reading a pdf file,
    File f=new File("D:/File.pdf");
                   FileReader fr=new FileReader(f);
                   BufferedReader br=new BufferedReader(fr);
                   String s=br.readLine();any help will be deeply appreciated.

    jverd wrote:
    First, you set i once, and then loop without ever changing it. So your loop body will execute either 0 times or infinitely many times, writing the same byte every time. Actually, maybe it'll execute once and then throw an ArrayIndexOutOfBoundsException. That's basic java looping, and you're going to need a firm grip on that before you try to do anything as advanced as PDF reading. the case.oops you are absolutely right that was a silly mistake to forget that,
    Second, what do the docs for getPageContent say? Do they say that it simply gives you the text on the page as if the thing were a simple text doc? I'd be surprised if that's the case.getPageContent return array of bytes so the question will be:
    how to get text from this array? i was thinking of :
        private void jButton1_actionPerformed(ActionEvent e) {
            PdfReader read;
            StringBuffer buff=new StringBuffer();
            try {
                read = new PdfReader("d:/getjobid2727.pdf");
                read.getMetaData();
                byte[] data=read.getPageContent(1);
                int i=0;
                while(i>-1){ 
                    buff.append(data);
    i++;
    String str=buff.toString();
    FileOutputStream fos = new FileOutputStream("D:/test.txt");
    Writer out = new OutputStreamWriter(fos, "UTF8");
    out.write(str);
    out.close();
    read.close();
    } catch (Exception f) {
    f.printStackTrace();
    "D:/test.txt"  hasn't been created!! when i ran the program,
    is my steps right?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Reading Java files from a EAR file

    I want to read all Java files from a EAR file and from inner (inside EAR) EAR or WAR file with out unpacking.
    suppose "Demo.ear" contaions the following files:
    abc.java
    programs / a.java
    programs / b.java
    src / index.java
    src / com / myFolder / main.java
    src.war
    and suppose "src.war" again contains some java files inside differenet folders.
    The main problem is that i can read all java files from "Demo.ear" but unable to reading from "src.war" b'coz my program is using JarFile class constructor which needs a archive file path, So only top level archive having the path but not the inner archives.
    So, pls help me out to this problems
    Thanks in advance

    Maybe you can use java.util.zip.ZipInputStream to
    open the Ear and recursively to open the files in
    it; I'm not sure whether this will result in a full
    unpacking of the file in some temporary directory,
    though.
    Please let me know if it worked the way you wanted,
    I'm curious about it.This jerk just created the third thread about the same topic, because he didn't understand your suggestion, which I already provided earlier.
    http://forum.java.sun.com/thread.jspa?threadID=790015

  • Hi i am new to labview. i want to extract data from a text file and display it on the front panel. how do i proceed??

    Hi i am new to labview
    I want to extract data from a text file and display it on the front panel.
    How do i proceed??
    I have attached a file for your brief idea...
    Attachments:
    extract.jpg ‏3797 KB

    RoopeshV wrote:
    Hi,
    The below code shows how to read from txt file and display in the perticular fields.
    Why have you used waveform?
    Regards,
    Roopesh
    There are so many things wrong with this VI, I'm not even sure where to start.
    Hard-coding paths that point to your user folder on the block diagram. What if somebody else tries to run it? They'll get an error. What if somebody tries to run this on Windows 7? They'll get an error. What if somebody tries to run this on a Mac or Linux? They'll get an error.
    Not using Read From Spreadsheet File.
    Use of local variables to populate an array.
    Cannot insert values into an empty array.
    What if there's a line missing from the text file? Now your data will not line up. Your case structure does handle this.
    Also, how does this answer the poster's question?

  • Java files from a EAR file and from inner (inside EAR)

    I want to read all Java files from a EAR file and from inner (inside EAR) EAR or WAR file with out unpacking.
    suppose "Demo.ear" contaions the following files:
    abc.java
    programs / a.java
    programs / b.java
    src / index.java
    src / com / myFolder / main.java
    src.war
    and suppose "src.war" again contains some java files inside differenet folders.
    The main problem is that i can read all java files from "Demo.ear" but unable to reading from "src.war" b'coz my program is using JarFile class constructor which needs a archive file path, So only top level archive having the path but not the inner archives.
    So, pls help me out to this problems
    Thanks in advance

    Firstly Sorry to writing long letter. but i was unable to express my problem.
    see my code==============================
    JarFile jarFile = new JarFile("Demo.ear");
    Enumeration e=jarFile.entries();
    while (e.hasMoreElements())
    JarEntry entry=(JarEntry)e.nextElement();
    if (entry.getName().endsWith(".war"))
    // Then what Next to do...........
    ===========================================
    you have mentioned "theFile" , What is this?...............
    InputStream in = theFile.getInputStream(theEntryOfTheWAR);
    This line is not a compatible type casting in Java..........
    ZipOutputStream theWar = new ZipInputStream(in);

  • Java files from a EAR file

    I want to read all Java files from a EAR file and from inner (inside EAR) EAR or WAR file with out unpacking.
    suppose "Demo.ear" contaions the following files:
    abc.java
    programs / a.java
    programs / b.java
    src / index.java
    src / com / myFolder / main.java
    src.war
    and suppose "src.war" again contains some java files inside differenet folders.
    The main problem is that i can read all java files from "Demo.ear" but unable to reading from "src.war" b'coz my program is using JarFile class constructor which needs a archive file path, So only top level archive having the path but not the inner archives.
    So, pls help me out to this problems
    Thanks in advance

    please help me
    I am waiting for ur response
    thanking you

  • Extract hierarchy from a flat file

    Hello,
    I’m trying to extract hierarchy from a flat file.
    The hierarchy is built from 3 different infoObjects each infoObject represent different level in the hierarchy. I built the hierarchy in the last level of the hierarchy and put all the levels as external chars in the hierarchy.
    (I used the blog: Hierarchy Upload from Flat files: /people/prakash.bagali/blog/2006/02/07/hierarchy-upload-from-flat-files )
    When I extract the data into the PSA it looks fine but when I choose to  update the PSA data into the infoObject  the request stays yellow. Three is no dump and I cant find the job in SM50.
    Please Advice,
    David

    Hi David,
    Thats the problem with using PSA for flatfile hierarchy loads. If you can change the transfer method to "IDOC" then change and retry the load. The IDoc method gives you an advantrage when dealing with flatfiles as you can debug and notice which record # has errors.
    Bye
    Dinesh

  • Booting from a tar file

    Hi
    I have to install a new version on a AP and i just downloaded a .tar file from Cisco.
    My question is, can i boot directly from that tar file?
    I never tryied this and before doing something wrong i want to be sure it will work. I read somewhere that maybe i have to uncompress the file firt but the AP seems it doesn't have this option.
    Any help will be great, thanks

    What files do you have in your flash memory? Can you list them on here.
    Is the AP still accessible over the network?
    Did you load the .tar file directly onto the AP?
    If so then it will not boot with this file. a .tar file is the Cisco equivalent of a ZIP file. Before you can use it you need to "unzip" it. The problem is that the AP doesn't have enough memory to hold the .tar file and the unzipped files. Your best bet may be to copy the .bin file from one of your other access points onto this AP to get it to boot, then use the command in my original post. I've used this command on 130 AP1200s without a single problem.

  • Hello Anybody, I have a question. Can any of you please suggest me how to make an xml file from the database table with all the rows? Note:- I am having the XSD Schema file and the resulted XML file should be in that XSD format only.

    Hello Anybody, I have a question. Can any of you please suggest me how to make an xml file from the database table with all the records?
    Note:- I am having the XSD Schema file and the resulted XML file should be in that XSD format only.

    The Oracle documentation has a good overview of the options available
    Generating XML Data from the Database
    Without knowing your version, I just picked 11.2, so you made need to look for that chapter in the documentation for your version to find applicable information.
    You can also find some information in XML DB FAQ

Maybe you are looking for

  • How can I add a new user to my managed account?

    *There is an existing skype user.  i.e She already has a skype account *I have a Skype Manager account and want to provide her with SkypeCredit *I am having trouble doing that.  It seems that I can add a new member to my group only if they are a new

  • ItunesSetup wont open

    I am on windows xp and have had itunes for a while, i was with version 8.1 i think and it worked fine with my ipod classic, i recently bought my friends ipod touch and so now i need itunes 9, when i tried to update it always went to about 80% and sai

  • Opening a file in its native application from Flex.

    Is it possible to open a file on whatever native application the user runs it as?  Or even, at that, to simply open the directory it's in, in an explorer window? We have a search application and the frontend is in Flex, and I'm trying to find a way t

  • How to include the timeline counter in the sequence

    PPCS4 This sounds asif it ought to be simple, yet I can't find a way to do it! How do I show the timeline counter in the  sequence? I want to create a DVD of project and include the time count on screen. Can anyone help? Cheers

  • I cant read my backup after an 'erase and install' !!

    I backed up with time machine, erased and installed my mac. Now i'm manually looking for files and I do not have 'certain privileges' for some folders! (folder has a small red sign on it at the bottom) help please? =D