2

我正在使用 java.jar 将文件替换到现有的 jar 文件中。当我替换新文件时,剩余文件修改时间也更改为当前时间戳。请告知需要做些什么来保留其他文件的原始修改日期时间。我正在使用代码,

    while (entry != null) {
        String name = entry.getName();
        boolean notInFiles = true;
        for (File f : files) {
            if (f.getName().equals(name)) {
                notInFiles = false;
                break;
            }
        }
                    if (notInFiles) {
            // Add ZIP entry to output stream.
            out.putNextEntry(new ZipEntry(name));
            // Transfer bytes from the ZIP file to the output file
            int len;
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
        entry = zin.getNextEntry();
    }
    // Close the streams        
    zin.close();
    // Compress the files
    for (int i = 0; i < files.length; i++) {
        InputStream in = new FileInputStream(files[i]);
        // Add ZIP entry to output stream.
        out.putNextEntry(new ZipEntry(files[i].getName()));
        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        // Complete the entry
        out.closeEntry();
        in.close();
    }
4

1 回答 1

1

由于 Jar 文件基本上是具有不同文件类型扩展名的 zip 文件,因此您可以使用ZipFileSystemProvider将 jar 文件挂载为java.nio.file.FileSystem

然后使用Files.copy(fromPath,toPath,replace)复制文件。这将使 jar 中的其他文件保持不变,并且可能会快很多。

public class Zipper {

    public static void main(String [] args) throws Throwable {
        Path zipPath = Paths.get("c:/test.jar");

        //Mount the zipFile as a FileSysten
        try (FileSystem zipfs = FileSystems.newFileSystem(zipPath,null)) {

            //Setup external and internal paths
            Path externalTxtFile = Paths.get("c:/test1.txt");
            Path pathInZipfile = zipfs.getPath("/test1.txt");          

            //Copy the external file into the zipfile, Copy option to force overwrite if already exists
            Files.copy(externalTxtFile, pathInZipfile,StandardCopyOption.REPLACE_EXISTING);

            //Close the ZipFileSystem
            zipfs.close();
        } 
    }
}
于 2013-01-10T10:11:45.320 回答