title: Decompress Gzip file and store in variable
body: <p>I have searched a lot for conversion from byte to string but my query is a little different, please read ahead.</p>
  
  <p>Currently i have a gzip file which i can decompress using the code from <a href="http://www.mkyong.com/java/how-to-decompress-file-from-gzip-file/" rel="nofollow noreferrer">http://www.mkyong.com/java/how-to-decompress-file-from-gzip-file/</a>.
  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:</p>
  
  <pre><code>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)) &gt; 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;
          }
      } 
  </code></pre>
  
  <p>Since i am converting bytes to string near the end when <code>bytes_read</code> 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 <code>fileOutputStream.write(buffer, 0, bytes_read);</code> limits it to writing the updated part.
  How do i fix this?</p>
  
  <p>Thanks in advance.</p>