我正在使用java将文件替换为现有的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();
}
答案 0 :(得分:1)
由于Jar文件是具有不同文件类型扩展名的基本zip文件,您可以使用java.nio.file.FileSystem
将jar文件挂载为ZipFileSystemProvider然后使用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();
}
}
}