Java – batch decompression GZ file

I have 100 GZ file, I need to unzip it

a) I use http://www.roseindia.net/java/beginners/JavaUncompress.shtml The given code is decompressed GZ file It works normally Task: - is there any way to get the file name of the compressed file I know that the zip class of Java gives the enumeration of entry files This can be stored for me Zip file name, size, etc However, for GZ file are we the same? Or file name and filename GZ is the same and deleted gz.

b) Is there another elegant way to decompress by calling utility functions in Java code GZ file It's like calling a 7 - Zip application from a Java class Then, I don't have to worry about input / output streams

Thank you in advance Kappil

Solution

a) Zip is an archive format, but gzip is not Therefore, unless, for example, your GZ file is a compressed tar file, the entry iterator doesn't make much sense What you want may be:

File outFile = new File(infile.getParent(),infile.getName().replaceAll("\\.gz$",""));

b) Do you just want to unzip the file? If not, you can use gzipinputstream to read the file directly, that is, there is no need for intermediate decompression

But no problem Suppose you really just want to unzip the file If so, you can use this:

public static File unGzip(File infile,boolean deleteGzipfileOnSuccess) throws IOException {
    GZIPInputStream gin = new GZIPInputStream(new FileInputStream(infile));
    FileOutputStream fos = null;
    try {
        File outFile = new File(infile.getParent(),""));
        fos = new FileOutputStream(outFile);
        byte[] buf = new byte[100000];
        int len;
        while ((len = gin.read(buf)) > 0) {
            fos.write(buf,len);
        }

        fos.close();
        if (deleteGzipfileOnSuccess) {
            infile.delete();
        }
        return outFile; 
    } finally {
        if (gin != null) {
            gin.close();    
        }
        if (fos != null) {
            fos.close();    
        }
    }       
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>