如何在Java中获取gzip内文件的时间戳

如何在Java中获取gzip内文件的时间戳,java,gzip,compression,Java,Gzip,Compression,我想保留从Java中的gzip文件提取的文件的时间戳 代码如下: public void gunzipFile(String zipFile, String newFile) { System.out.println("zipFile: " + zipFile); final int bufferSize = 1024; try { FileInputStream fis = new FileInputStream(zipFile);

我想保留从Java中的gzip文件提取的文件的时间戳

代码如下:

   public void gunzipFile(String zipFile, String newFile) {
    System.out.println("zipFile: " + zipFile);
    final int bufferSize = 1024;
    try {
        FileInputStream fis = new FileInputStream(zipFile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        GZIPInputStream gis = new GZIPInputStream(bis);
        FileOutputStream fos = new FileOutputStream(newFile);
        final byte[] buffer = new byte[bufferSize];
        int len = 0;
        while ((len = gis.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        //close resources
        fos.close();
        gis.close();
    } catch (IOException e) {
        System.out.println("exception caught");
    }
}

这是一个很有技巧的解决方案,因为
GZIPInputStream
类不能给您时间戳

FileInputStream fis = new FileInputStream(zipFile);
byte[] header = new byte[10];
fis.read(header);

int timestamp = header[4] & 0xFF |
            (header[5] & 0xFF) << 8 |
            (header[6] & 0xFF) << 16 |
            (header[7] & 0xFF) << 24; 

// or more simply, use
// int timestamp = ByteBuffer.wrap(header, 4, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();

System.out.println(new Date((long) timestamp * 1000)); // this will give you the date
换句话说,第一个字节是
int
的最后8位。这就是
LITTLE_ENDIAN
的用武之地


我建议您小心使用此处的
InputStream
。可能使用
BufferedInputStream
reset()
定位
0
,或者只打开一个不同的
InputStream
。使用其中一个获取时间戳,使用另一个为gzip内容充气。

@Marvado不客气。如果它涵盖了一切,请考虑接受答案。
    0        1
+--------+--------+
|00001000|00000010|
+--------+--------+
 ^        ^
 |        |
 |        + more significant byte = 2 x 256
 + less significant byte = 8