2013-01-10 22 views
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(); 
    } 

回答

1

成JAR-文件與不同的文件類型的擴展名basicly zipfiles,您可以使用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(); 
     } 
    } 
} 
+0

由於JDK 7支持FileSystems並且我當前使用JDK 6版本,因此我無法遵循此方法。請按照相同的方式提醒。 – nitinverma

相關問題