1

我遵循以下方法使用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 的回答的帮助下,以下更改将使其工作。

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

1 回答 1

1

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

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

于 2019-01-22T09:43:15.213 回答