javastringbytegzipinputstream

Decompress Gzip file and store in variable


I have searched a lot for conversion from byte to string but my query is a little different, please read ahead.

Currently i have a gzip file which i can decompress using the code from http://www.mkyong.com/java/how-to-decompress-file-from-gzip-file/. This code helps me store my decompressed output in a file, but how do i store it in a variable? I am using this code currently:

public String unGunzipFile(String compressedFile, String decompressedFile) {

        byte[] buffer = new byte[1024];

        try {

            FileInputStream fileIn = new FileInputStream(compressedFile);

            GZIPInputStream gZIPInputStream = new GZIPInputStream(fileIn);

            FileOutputStream fileOutputStream = new FileOutputStream(decompressedFile);
            StringBuffer str = new StringBuffer();
            int bytes_read;
            while ((bytes_read = gZIPInputStream.read(buffer)) > 0) {

                String s = new String(buffer);
                str.append(s);
                fileOutputStream.write(buffer, 0, bytes_read);
            }

            gZIPInputStream.close();
            fileOutputStream.close();

            System.out.println("The file was decompressed successfully!");
            System.out.println(str);
            String final_string = str.toString();
            return final_string;

        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    } 

Since i am converting bytes to string near the end when bytes_read is not 1024 in length i end up getting some weird data in my StringBuffer, but in the file there is no such data since fileOutputStream.write(buffer, 0, bytes_read); limits it to writing the updated part. How do i fix this?

Thanks in advance.


Solution

  • Use the String(byte[] bytes, int offset, int length) constructor that lets you specify the length to be converted. i.e.

    String s = new String(buffer, 0, bytes_read)