2013-03-19 123 views
0

我有一個使用BZip2壓縮文件然後將其保存到新文件的程序。無法解壓縮使用BZip2壓縮的文件

Public Sub Create(ByVal outPathname As String, ByVal filePath As String) 
    Dim msCompressed As New MemoryStream() 
    Dim zosCompressed As New BZip2OutputStream(msCompressed) 
    Dim fileInput As New FileStream(filePath, FileMode.Open) 
    Dim buffer As Byte() = GetStreamAsByteArray(fileInput) 
    zosCompressed.Write(buffer, 0, buffer.Length) 
    zosCompressed.Flush() 
    zosCompressed.Close() 
    buffer = msCompressed.ToArray() 
    Dim FileOutput As New FileStream(outPathname, FileMode.Create, FileAccess.Write) 
    FileOutput.Write(buffer, 0, buffer.LongLength) 
    FileOutput.Flush() 
    FileOutput.Close() 
End Sub 

但我似乎無法弄清楚爲什麼我無法解壓縮它創建的文件。有人可以告訴我我的解壓縮程序有什麼問題嗎? (這是在比壓縮機一個單獨的程序。)

Public Sub Extract(ByVal archiveFilenameIn As String, ByVal outFolder As String) 
    Dim fileInput As New FileStream(archiveFilenameIn, FileMode.Open) 
    Dim msUncompressed As New MemoryStream(GetStreamAsByteArray(fileInput)) 
    Dim zosDecompressed As New BZip2InputStream(msUncompressed) 
    Dim buffer As Byte() = GetStreamAsByteArray(fileInput) 
    zosDecompressed.Read(buffer, 0, buffer.Length()) 
    buffer = msUncompressed.ToArray() 
    Dim FileOutput As New FileStream(outFolder & "\temporary.bmp", FileMode.Create, FileAccess.Write) 
    FileOutput.Write(buffer, 0, buffer.LongLength) 
    FileOutput.Flush() 
    FileOutput.Close() 
    zosDecompressed.Close() 
    msUncompressed.Close() 
    fileInput.Close() 
End Sub 

編輯:我還使用一個功能流轉換爲字節數組的位置:

Private Function GetStreamAsByteArray(ByVal stream As System.IO.Stream) As Byte() 
    Dim streamLength As Integer = Convert.ToInt32(stream.Length) 
    Dim fileData As Byte() = New Byte(streamLength) {} 

    ' Read the file into a byte array 
    stream.Read(fileData, 0, streamLength) 
    stream.Close() 

    Return fileData 
End Function 

幫助?

回答

0

嘗試在使用寫入數據之前完成BZip2OutputStream。這對我很有幫助。

zosCompressed.Finalize(); 
buffer = msCompressed.ToArray(); 

BZip2OutputStream usage example

+0

這樣做的用處是有限的,因爲調用'Finalize()'關閉底層內存流並完全破壞了壓縮內存流的目的。 – ajeh 2016-05-17 20:37:14