Java zipping is changing the date of the created file

Viewed 1363

I have used the below code copied from https://www.mkyong.com/java/how-to-compress-files-in-zip-format/ to create a Zip file

When the zip file is created the entry gets the date when the zip file is actually created. However i want to maintain the original file's dates. I am on Mac OS and using java 1.7

I can think of setting the zip entry's dates by reading the file attributes. But is this the right way to maintain the date while zipping ?

   package org.saurav.simpletests.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Zipper {


    public static void main( String[] args )
    {
        byte[] buffer = new byte[1024];

        try{

            FileOutputStream fos = new FileOutputStream("/Users/xxxx/Documents/Work//Data/Zipper/test.zip");
            ZipOutputStream zos = new ZipOutputStream(fos);
            ZipEntry ze= new ZipEntry("Sonar_Gerrit_Issue.png");

            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream("/Users/xxxx/Documents/Work/Data/Zipper/Sonar_Gerrit_Issue.png");
            File file  = new File("/Users/i054564/Documents/Work/Data/Zipper/Sonar_Gerrit_Issue.png");

            int len;;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }

            in.close();
            zos.closeEntry();

            //remember close it
            zos.close();

            System.out.println("Done");

        }catch(IOException ex){
           ex.printStackTrace();
        }
    }
}
2 Answers

You need to set the date while zipping as follows:

File file = new File("Sonar_Gerrit_Issue.png");
ZipEntry ze = new ZipEntry(file);
ze.setTime(file.lastModified());

The same is required for unzipping:

File file = //unzipping here for ZipEntry ze
file.setLastModified(ze.getTime());

Since you are using Java 1.7 you could use FileSystem API, which will save you time.

In example:

    Path zipFilePath = Paths.get("PathToZip");
    try (FileSystem fs = FileSystems.newFileSystem(zipFilePath, null)) {
        Path source = new File("pathToSonar_Gerrit_IssuePNG").toPath(); //external file
        Path dest = fs.getPath("/Sonar_Gerrit_Issue.png"); //file in the zip
        Files.setLastModifiedTime(source, Files.getLastModifiedTime(dest)); //copy modified attribute
        Files.copy(source, dest, StandardCopyOption.COPY_ATTRIBUTES ,StandardCopyOption.REPLACE_EXISTING);  //copy with replace option
    }

Note: Replace paths to fits your needs.

Related