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

时间:2013-09-25 15:11:18

标签: 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);
        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");
    }
}

1 个答案:

答案 0 :(得分:2)

这是一个hacky解决方案,因为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

GZIP format对某些元数据使用10字节标头。字节5(偏移4)到8表示unix时间戳。如果将它们转换为int并乘以1000得到毫秒,则可以获得文件的日期(如果最初的那个)。

格式为

    0        1
+--------+--------+
|00001000|00000010|
+--------+--------+
 ^        ^
 |        |
 |        + more significant byte = 2 x 256
 + less significant byte = 8

换句话说,第一个字节是int的最后8位。这就是LITTLE_ENDIAN进来的地方。

我建议你小心使用这里的InputStream。可能会使用BufferedInputStreamreset()来定位0或只是打开另一个InputStream。使用一个来获取时间戳并使用另一个来膨胀gzip内容。