Java Ungzip decompressGzipString(String gzipFile)

Here you can find the source of decompressGzipString(String gzipFile)

Description

decompressGzipString -- Decompress a .gz file into a String.

License

Apache License

Parameter

Parameter Description
gzipFile a parameter

Return

String version of the file

Declaration

public static String decompressGzipString(String gzipFile) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010, 2012 Institute for Dutch Lexicology
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.//from   w  ww. j av a  2  s. co m
 *******************************************************************************/

import java.io.ByteArrayOutputStream;

import java.io.FileInputStream;

import java.io.IOException;

import java.util.zip.GZIPInputStream;

public class Main {
    /**
     * The default encoding for opening files.
     */
    private static String defaultEncoding = "utf-8";

    /**
     * decompressGzipString -- 
     *    Decompress a .gz file into a String.
     * 
     * See: http://www.journaldev.com/966/java-gzip-example-compress-and-decompress-file-in-gzip-format-in-java
     * 
     * @param gzipFile
     * @return String version of the file
     */
    public static String decompressGzipString(String gzipFile) {
        try {
            FileInputStream fis = new FileInputStream(gzipFile);
            ByteArrayOutputStream bos;
            try (GZIPInputStream gis = new GZIPInputStream(fis)) {
                bos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = gis.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
                //close resources
                bos.close();
            }
            // Convert byte output into string
            return bos.toString(defaultEncoding);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }

    }
}

Related

  1. decompressGZIP(String sourceFilename, String targetFilename)
  2. decompressGzipFile(String gzipFile, String newFile)