我对Java的GZip有一个问题。目前,我处理的文件是gzipped。一个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");
}我还尝试了新的GZIPInputStream(新FileInputStream(baseFile));结果是一样的。由于输出,我看到Gzip流毫无例外地创建,但后来我从DataInputStream获得无效数据。(请帮助:)
发布于 2016-09-15 07:57:53
我运行了以下代码,没有问题
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文件和未压缩文件,并比较内容。它打印不同的文件:假。如果不是因为你的文件比文件不一样的话。
发布于 2016-09-15 11:59:06
我的最后解决办法是:
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;
}https://stackoverflow.com/questions/39505565
复制相似问题