Dear All,

I have a tar file which contains .Z files. File Structure is : x.tar -> [1.Z, 2.Z]. I need to read data from this zip files.

So far I have reached a stage where I read entry from tar but am not able to unzip files within the tar. Please can you help. My code is below.

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;

/***
 * Extracts Tar file
 * @author Aditya.YAGNIK
 *
 */
class TarExtractor{
	public void extract() throws IOException{
		String filePath = "file.tar";
		FileInputStream fis = new FileInputStream(new File(filePath));
		BufferedInputStream bis = new BufferedInputStream(fis); 
		try {
			ArchiveInputStream input = new ArchiveStreamFactory().createArchiveInputStream(bis);
			if (input instanceof TarArchiveInputStream){
				System.out.println("It is a tar input stream");
				TarArchiveInputStream tarInput = (TarArchiveInputStream)input; 
				TarArchiveEntry entry = tarInput.getNextTarEntry();
				while (entry != null) {
                    String name = entry.getName();
                    System.out.println("Entry: " + name  );
                    entry = tarInput.getNextTarEntry();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}


	}
	public static void main(String[] args) throws IOException{
		TarExtractor t = new TarExtractor();
		t.extract();
	}
}

Look into the java.util.zip import.

You can then use the GZIPInputStream/GZIPOutputStream with your stream:

InputStream in = new GZIPInputStream(new FileInputStream(file));

I've also seen the TarInputStream being used before. There are a few tutorials out there:

The class file:
http://www.jajakarta.org/ant/ant-1.6.1/docs/en/manual/api/org/apache/tools/tar/TarInputStream.html

Oracle:
http://java.sun.com/developer/technicalArticles/Programming/compression/

Dev Daily:
http://www.devdaily.com/java/jwarehouse/javatar-2.5/source/com/ice/tar/TarInputStream.java.shtml

Good luck!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.