2010-12-11 10 views
7

Ho bisogno di creare l'archivio Bzip2. Una libreria bzip2 scaricata da 'Apache ant'.Java: libreria Bzip2

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

(non ho trovato alcun esempio come usarlo, così ho deciso di usarlo in questo modo)

ma crea un archivio danneggiato sul disco.

risposta

7

si deve aggiungere un'intestazione BZip2 (due byte: 'B', 'Z') prima di scrivere il contenuto:

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

Quindi, per esempio, è possibile estrarre il contenuto del file bzippati con cat compressed.bz2 | bunzip2 > uncompressed.txt su un sistema * nix.

+0

Questo è previsto, per ogni codice di Ant stesso: https://svn.apache.org/ viewvc/ant/core/trunk/src/main/org/apache/strumenti/ant/tipi/risorse/BZip2Resource.java? view = markup # L71 –

2

non ho trovato un esempio, ma alla fine ho capito come utilizzare CBZip2OutputStream ecco è 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(); 

    }