Java 有选择地从 zip 文件中复制文件,以便保留文件时间戳

Java selectively copy files from a zip such that file timestamp should be preserved

我按照以下方法使用 apache commons compress 解压缩 zip:

但由于我使用 OutputStream & IOUtils.copy(ais, os); (下面的代码) 来解压缩和复制文件,时间戳不会保留。有没有另一种方法可以直接从 zip 中复制文件,这样可以保留文件时间戳。

try (ArchiveInputStream ais =
         asFactory.createArchiveInputStream(
           new BufferedInputStream(
             new FileInputStream(archive)))) {

        System.out.println("Extracting!");
        ArchiveEntry ae;
        while ((ae = ais.getNextEntry()) != null) {
            // check if file needs to be extracted {}
            if(!extract())
                continue;

            if (ae.isDirectory()) {
                File dir = new File(archive.getParentFile(), ae.getName());
                dir.mkdirs();
                continue;
            }

            File f = new File(archive.getParentFile(), ae.getName());
            File parent = f.getParentFile();
            parent.mkdirs();
            try (OutputStream os = new FileOutputStream(f)) {
                IOUtils.copy(ais, os);
                os.close();
            } catch (IOException innerIoe) {
                ...
            }
        }

        ais.close();
        if (!archive.delete()) {
            System.out.printf("Could not remove archive %s%n",
                               archive.getName());
            archive.deleteOnExit();
        }
    } catch (IOException ioe) {
        ...
    }

编辑: 在下面 jbx's 答案的帮助下,以下更改将使它起作用。

IOUtils.copy(ais, os);
os.close();
outFile.setLastModified(entry.getLastModifiedTime().toMillis()); // this line

您可以使用 NIO 设置 lastModifiedTime 文件属性。 在您写入文件后(在您​​关闭它之后)对文件执行此操作。操作系统会将其最后修改时间标记为此时的当前时间。

https://docs.oracle.com/javase/tutorial/essential/io/fileAttr.html

您需要从 zip 文件中获取上次修改时间,因此可能使用 NIO 的 Zip Filesystem Provider` 来浏览和从存档中提取文件会比您当前的方法更好(除非您使用的 API 为您提供相同的信息)。

https://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html