簡體   English   中英

Java GzipInputStream轉換為DataInputStream

[英]Java GzipInputStream into DataInputStream

我在Java中遇到GZip問題。 目前,我正在處理壓縮文件。 一個gzip存檔中的一個文件。 如果我手動解壓縮它們,然后解析它們,則一切正常。 但是我想用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");
    }

我還嘗試了new GZIPInputStream(new FileInputStream(baseFile)); 結果是一樣的。 由於輸出,我看到Gzip流毫無例外地創建,但是后來我從DataInputStream獲取了無效數據。 請幫忙 :)

我運行以下代碼沒有問題

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文件和未壓縮的文件並比較內容。 它打印文件不同​​:false。 如果不是您的文件,則文件不相同。

我的最終解決方案:

    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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM