Search code examples
javazipunzip

Java: Maintaining zipped files Modified Date


A proprietary program that I'm working with zips up and extracts certain files without changing the modified date of the files when unzipping. I'm also creating my own zip and extraction tool based off the source code in our program but when I'm unzipping the files the modified date of all zipped files is showing with the unzip time & date. Here's the code for my extraction:

public static int unzipFiles(File zipFile, File extractDir) throws Exception 
{
        int totalFileCount = 0;
        String zipFilePath = zipFile.getPath();

        System.out.println("Zip File Path: " + zipFilePath);

        ZipFile zfile = new ZipFile(zipFile); 
        System.out.println("Size of ZipFile: "+zfile.size());

        Enumeration<? extends ZipEntry> entries = zfile.entries(); 

        while (entries.hasMoreElements()) 
        { 
          ZipEntry entry = entries.nextElement(); 
          System.out.println("ZipEntry File: " + entry.getName());
          File file = new File(extractDir, entry.getName()); 
          if (entry.isDirectory()) 
          { 
            System.out.println("Creating Directory");
            file.mkdirs(); 
          } 
          else 
          { 
            file.getParentFile().mkdirs(); 
            InputStream in = zfile.getInputStream(entry); 
            try 
            { 
              copy(in, file); 
            } 
            finally 
            {   
              in.close(); 
            } 
          } 
          totalFileCount++;
        }
        return totalFileCount; 
      } 

private static void copy(InputStream in, OutputStream out) throws IOException 

{

  byte[] buffer = new byte[1024]; 
  System.out.println("InputStream/OutputStram copy");
  while (true) 
  { 
    int readCount = in.read(buffer); 
    if (readCount < 0) 
    { 
      break; 
    } 
    out.write(buffer, 0, readCount); 
   } 
} 

I'm sure there is a better way to do this other than doing the inputstream/outputstream copy. I'm sure this is the culprit as doing an extraction with winRAR does not change the date with the files I zipped.


Solution

  • Use ZipEntry.getTime to get the last-modified time and File.setLastModified to set it on the file after you are done copying it.