2010-12-11 8 views
7

Necesito crear un archivo Bzip2. Una biblioteca bzip2 descargada de 'Apache hormiga'.Java: biblioteca Bzip2

I use class CBZip2OutputStream: 
String s = ..... 
CBZip2OutputStream os = new CBZip2OutputStream(fos); 
       os.write(s.getBytes(Charset.forName("UTF-8"))); 
       os.flush(); 
       os.close(); 

(No he encontrado ningún ejemplo de cómo usarlo, así que decidí usarlo de esta manera)

pero crea un archivo dañado en el disco.

Respuesta

7

hay que añadir cabecera BZip2 (dos bytes: 'B', 'Z') antes de escribir el contenido:

//Write 'BZ' before compressing the stream 
fos.write("BZ".getBytes()); 
//Write to compressed stream as usual 
CBZip2OutputStream os = new CBZip2OutputStream(fos); 
... the rest ... 

Entonces, por ejemplo, se puede extraer el contenido de su archivo bzip con cat compressed.bz2 | bunzip2 > uncompressed.txt en un sistema * nix.

+0

Se espera, por propio código de Ant: https://svn.apache.org/ viewvc/ant/core/trunk/src/main/org/apache/tools/ant/types/resources/BZip2Resource.java? view = markup # l71 –

2

no he encontrado un ejemplo, pero al final he entendido cómo utilizar CBZip2OutputStream así que aquí es uno:

public void createBZipFile() throws IOException{ 

     // file to zip 
     File file = new File("plane.jpg"); 

     // fichier compresse 
     File fileZiped= new File("plane.bz2"); 

     // Outputstream for fileZiped 
     FileOutputStream fileOutputStream = new FileOutputStream(fileZiped); 
     fileOutputStream.write("BZ".getBytes()); 

     // we getting the data in a byte array 
     byte[] fileData = getArrayByteFromFile(file); 

     CBZip2OutputStream bzip = null; 

     try{ 
      bzip = new CBZip2OutputStream(fileOutputStream); 

      bzip.write(fileData, 0, fileData.length); 
      bzip.flush() ; 
      bzip.close(); 

     }catch (IOException ex) { 

      ex.printStackTrace(); 
     } 



     fos.close(); 

    }