Jump to content

How to extract a subfolder in a gzip?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
RedBuLL

RedBuLL

    Newbie

  • Members
  • Pip
  • 2 posts
Hi, I have a .tar.gz file which contains a folder 'tree', and a file called 'log.txt' inside the folder 'tree'. I need to decompress the gzip to extract the log.txt.

Problem with my code is the first line of the output contains the path directory and some random numbers followed by the actual log.txt result. This is due to the folder 'tree' inside the gzip. Anyone who knows how to open the subfolder inside a gzip please help!!!! Thanks a lot.


import java.io.*;

import java.util.zip.*;

import org.apache.tools.ant.taskdefs.Untar;


public class Main {


    public static void main(String[] args) {

       try{

            GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream("C:\\myfile.tar.gz"));

            InputStream is = new Untar.UntarCompressionMethod().decompress("", gzipInputStream);


            byte[] iFile = new byte[1024];

            File f=new File("outFile");

            OutputStream out=new FileOutputStream(f);


            int len;

            while((len=is.read(iFile)) > 0)

            out.write(iFile,0,len);


            is.close();

            out.close();

        }

        catch(Exception e){

            e.printStackTrace();

        }

    }

}


Edited by dargueta, 18 October 2010 - 08:49 PM.
Added code tags


#2
discomonk

discomonk

    Newbie

  • Members
  • Pip
  • 7 posts
try this....
the following code assumes you are looking for file named "log.txt" in the archive:


import java.io.*;

import java.util.zip.*;

import org.apache.tools.tar.TarEntry;

import org.apache.tools.tar.TarInputStream;


public class ZipTest {


    public static void main(String[] args) {

       try{

            GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream("C:/log.tar.gz"));

            TarInputStream is =  new TarInputStream(gzipInputStream);

            

            

            


            File f=new File("outFile");

            OutputStream out=new FileOutputStream(f);



            TarEntry entry = null;

            while((entry = is.getNextEntry()) != null) {

            	

            	if (entry.getName().indexOf("log.txt") >= 0) {

            		is.copyEntryContents(out);

            	}


            }

            


            is.close();

            out.close();

        }

        catch(Exception e){

            e.printStackTrace();

        }

    }

}



#3
RedBuLL

RedBuLL

    Newbie

  • Members
  • Pip
  • 2 posts
Thanks discomonk. It works perfectly. :)