我想保留从 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");
}
}
最佳答案
这是一个 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 字节 header 。字节 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
。可以使用 BufferedInputStream
和 reset()
来定位 0
或仅打开不同的 InputStream
。使用一个来获取时间戳并使用另一个来膨胀 gzip 内容。
关于java - 如何在Java中获取gzip内文件的时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19008674/