2016-09-15 91 views
-1

我在Java中使用GZip時遇到問題。目前我使用gzip文件。一個gzip壓縮文件中的一個文件。如果我手動解壓他們,然後解析他們一切正常。但我想用Java和GZipInputStream自動執行此操作,但它不起作用。 我需要在最後有DataInputStream。我的代碼是:Java將GzipInputStream轉換爲DataInputStream

byte[] bytesArray = Files.readAllBytes(baseFile.toPath()); 

    try { 
     reader = new DataInputStream(new GZIPInputStream(new ByteArrayInputStream(bytesArray))); 
     System.out.println("gzip"); 
    } catch (ZipException notZip) { 
     reader = new DataInputStream(new ByteArrayInputStream(bytesArray)); 
     System.out.println("no gzip"); 
    } 

我也嘗試新的GZIPInputStream(新的FileInputStream(baseFile)); 結果是一樣的。由於輸出,我看到Gzip流創建無一例外,但後來我從DataInputStream無效的數據。 請幫助:)

+0

無效的數據,比如什麼呢?當有效數據應該是什麼?寫的如何? – EJP

+0

對不起:如果我使用原始文件或它的gzip版本,reader.readByte()會提供不同的結果。 – kapodes

回答

0

我跑到下面的代碼沒有問題

public static void main(String[] args) throws IOException { 
    byte[] originalBytesArray = Files.readAllBytes(new File("OrdLog.BR-1.17.2016-09-12.bin").toPath()); 
    byte[] bytesArray = Files.readAllBytes(new File("OrdLog.BR-1.17.2016-09-12.bin.gz").toPath()); 
    DataInputStream reader = null; 
    try { 
     reader = new DataInputStream(new GZIPInputStream(new ByteArrayInputStream(bytesArray))); 
     System.out.println("gzip"); 
    } catch (ZipException notZip) { 
     reader = new DataInputStream(new ByteArrayInputStream(bytesArray)); 
     System.out.println("no gzip"); 
    } 
    byte[] uncompressedBytesArray = new byte[originalBytesArray.length]; 
    reader.readFully(uncompressedBytesArray); 
    reader.close(); 
    boolean filesDiffer = false; 
    for (int i = 0; i < uncompressedBytesArray.length; i++) { 
     if (originalBytesArray[i] != uncompressedBytesArray[i]) { 
      filesDiffer = true; 
     } 
    } 
    System.out.println("Files differ: " + filesDiffer); 
} 

它讀取gzip文件和未壓縮的文件和內容進行比較。它打印文件不同​​:錯誤。如果它不適合你的文件而不是文件不一樣。

+0

我的問題是,我使用.readByte()方法,它似乎讀取不同的數據,如果我使用未壓縮的源。你可以測試這種方法並將其與原始文件進行比較嗎? – kapodes

+0

我跑了你的測試: gzip 文件不同:true。 7zip uncomplresses文件沒有問題,並說這是一個gzip壓縮文件。我沒有得到例外。 – kapodes

+0

我打算要求提供這個文件:-) Thx。閱讀壓縮文件時我犯了一個錯誤。我改變它使用readFully使代碼更容易。它沒有顯示任何差異 – Guenther

0

我的最終解決方案:

try { 
     byte[] gzipBytes = new byte[getUncompressedFileSize()]; 
     new DataInputStream(new GZIPInputStream(new FileInputStream(baseFile))).readFully(gzipBytes); 
     reader = new DataInputStream(new ByteArrayInputStream(gzipBytes)); 
    } catch (ZipException notZip) { 
     byte[] bytesArray = Files.readAllBytes(baseFile.toPath()); 
     reader = new DataInputStream(new ByteArrayInputStream(bytesArray)); 
    } 

private int getUncompressedFileSize() throws IOException { 
    //last 4 bytes of file is size of original file if it is less than 2GB 
    RandomAccessFile raf = new RandomAccessFile(baseFile, "r"); 
    raf.seek(raf.length() - 4); 
    int b4 = raf.read(); 
    int b3 = raf.read(); 
    int b2 = raf.read(); 
    int b1 = raf.read(); 
    int val = (b1 << 24) | (b2 << 16) + (b3 << 8) + b4; 
    raf.close(); 
    return val; 
}