2010-12-11 35 views
7

Tôi cần tạo bản lưu trữ Bzip2. Thư viện bzip2 đã tải xuống từ 'Apache ant'.Java: Thư viện Bzip2

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

(tôi không tìm thấy bất kỳ ví dụ làm thế nào để sử dụng nó, vì vậy tôi quyết định sử dụng nó theo cách này)

Nhưng nó tạo ra một kho lưu trữ bị hỏng trên đĩa.

Trả lời

7

Bạn phải thêm BZip2 tiêu đề (hai byte: 'B', 'Z') trước khi viết nội dung:

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

Sau đó, ví dụ, bạn có thể trích xuất nội dung của file bzipped của bạn với cat compressed.bz2 | bunzip2 > uncompressed.txt trên một hệ thống * nix.

+0

này được mong đợi, mỗi mã Ant bản thân: https://svn.apache.org/ viewvc/ant/core/trunk/src/main/org/apache/công cụ/kiến ​​/ loại/tài nguyên/BZip2Resource.java? view = markup # l71 –

2

tôi đã không tìm thấy một ví dụ nhưng cuối cùng tôi đã hiểu làm thế nào để sử dụng CBZip2OutputStream vì vậy đây là một trong:

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(); 

    }