2016-09-15 41 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; 
}