Saltar al contenido

Compresión GZIP a un byte array

La guía o código que hallarás en este post es la solución más sencilla y válida que hallamos a tus dudas o problema.

Solución:

El problema es que no estás cerrando el GZIPOutputStream. Hasta que lo cierre, la salida estará incompleta.

solo tienes que cerrarlo antes de leyendo el byte array. Necesitas reordenar el finally bloques para lograrlo.

import java.io.*;
import java.util.zip.*;
import java.nio.charset.*;

public class Zipper

  public static void main(String[] args)
      
    byte[] dataToCompress = "This is the test data."
      .getBytes(StandardCharsets.ISO_8859_1);

    try
    
      ByteArrayOutputStream byteStream =
        new ByteArrayOutputStream(dataToCompress.length);
      try
      
        GZIPOutputStream zipStream =
          new GZIPOutputStream(byteStream);
        try
        
          zipStream.write(dataToCompress);
        
        finally
        
          zipStream.close();
        
      
      finally
      
        byteStream.close();
      

      byte[] compressedData = byteStream.toByteArray();

      FileOutputStream fileStream =
        new FileOutputStream("C:/Users/UserName/Desktop/zip_file.gz");
      try
      
        fileStream.write(compressedData);
      
      finally
      
        try fileStream.close(); 
          catch(Exception e) /* We should probably delete the file now? */ 
      
    
    catch(Exception e)
    
      e.printStackTrace();
    
  

No recomiendo inicializar las variables de flujo para nullporque significa tu finally bloque también puede lanzar un NullPointerException.

También tenga en cuenta que puede declarar main tirar IOException (entonces no necesitarías el más externo try declaración.)

No tiene mucho sentido aceptar las excepciones de zipStream.close();porque si arroja una excepción no tendrá un archivo .gz válido (por lo que no debe proceder a escribirlo).

Además, no aceptaría excepciones de byteStream.close(); pero por una razón diferente: nunca deben lanzarse (es decir, hay un error en su JRE y le gustaría saber sobre eso).

He mejorado el código de JITHINRAJ: usé probar con recursos:

private static byte[] gzipCompress(byte[] uncompressedData) 
        byte[] result = new byte[];
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream(uncompressedData.length);
             GZIPOutputStream gzipOS = new GZIPOutputStream(bos)) 
            gzipOS.write(uncompressedData);
            // You need to close it before using bos
            gzipOS.close();
            result = bos.toByteArray();
         catch (IOException e) 
            e.printStackTrace();
        
        return result;
    

private static byte[] gzipUncompress(byte[] compressedData) 
        byte[] result = new byte[];
        try (ByteArrayInputStream bis = new ByteArrayInputStream(compressedData);
             ByteArrayOutputStream bos = new ByteArrayOutputStream();
             GZIPInputStream gzipIS = new GZIPInputStream(bis)) 
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gzipIS.read(buffer)) != -1) 
                bos.write(buffer, 0, len);
            
            result = bos.toByteArray();
         catch (IOException e) 
            e.printStackTrace();
        
        return result;
    

Si todavía está buscando una respuesta, puede usar el siguiente código para obtener el byte comprimido[] usando el desinflador y descomprímalo usando el inflador.

public static void main(String[] args) 
        //Some string for testing
        String sr = new String("fsdfesfsfdddddddsfdsfssdfdsfdsfdsfdsfdsdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggghghghghggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggfsdfesfsfdddddddsfdsfssdfdsfdsfdsfdsfdsdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggghghghghggggggggggggggggggggggggggggggggggggggggg");
        byte[] data = sr.getBytes();
        System.out.println("src size "+data.length);
        try 
            compress(data);
         catch (IOException e) 
            // TODO Auto-generated catch block
            e.printStackTrace();
        
    
    public static byte[] compress(byte[] data) throws IOException  
        Deflater deflater = new Deflater(); 
        deflater.setInput(data); 
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);  

        deflater.finish(); 
        byte[] buffer = new byte[1024];  
        while (!deflater.finished())  
        int count = deflater.deflate(buffer);  
        outputStream.write(buffer, 0, count);  
         
        outputStream.close(); 
        byte[] output = outputStream.toByteArray(); 

        System.out.println("Original: " + data.length  ); 
        System.out.println("Compressed: " + output.length ); 
        return output; 
           

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *