Home » Java » Copy and validate a Zip File via Java

Copy and validate a Zip File via Java

Posted by: admin December 28, 2021 Leave a comment


After some research:

How to create a Zip File

and some google research i came up with this java function:

 static void copyFile(File zipFile, File newFile) throws IOException {
    ZipFile zipSrc = new ZipFile(zipFile);
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(newFile));

    Enumeration srcEntries = zipSrc.entries();
    while (srcEntries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) srcEntries.nextElement();
            ZipEntry newEntry = new ZipEntry(entry.getName());

            BufferedInputStream bis = new BufferedInputStream(zipSrc

            while (bis.available() > 0) {


This code is working…but it is not nice and clean at all…anyone got a nice idea or an example?


I want to able to add some type of validation if the zip archive got the right structure…so copying it like an normal file without regarding its content is not working for me…or would you prefer checking it afterwards…i am not sure about this one


You just want to copy the complete zip file? Than it is not needed to open and read the zip file… Just copy it like you would copy every other file.

public final static int BUF_SIZE = 1024; //can be much bigger, see comment below

public static void copyFile(File in, File out) throws Exception {
  FileInputStream fis  = new FileInputStream(in);
  FileOutputStream fos = new FileOutputStream(out);
  try {
    byte[] buf = new byte[BUF_SIZE];
    int i = 0;
    while ((i = fis.read(buf)) != -1) {
        fos.write(buf, 0, i);
  catch (Exception e) {
    throw e;
  finally {
    if (fis != null) fis.close();
    if (fos != null) fos.close();


Try: http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html#copyFile
Apache Commons FileUtils#copyFile


My solution:

import java.io.*;
import javax.swing.*;
public class MovingFile
    public static void copyStreamToFile() throws IOException
        FileOutputStream foutOutput = null;
        String oldDir =  "F:/UPLOADT.zip";
        String newDir = "F:/NewFolder/UPLOADT.zip";  // name as the destination file name to be done
        File f = new File(oldDir);
        f.renameTo(new File(newDir));
    public static void main(String[] args) throws IOException


I have updated your code to Java 9+, FWIW

   try (ZipFile srcFile = new ZipFile(inputName)) {
        try (ZipOutputStream destFile = new ZipOutputStream(
                Files.newOutputStream(Paths.get(new File(outputName).toURI())))) {
            Enumeration<? extends ZipEntry> entries = srcFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry src = entries.nextElement();
                ZipEntry dest = new ZipEntry(src.getName());
                try (InputStream content = srcFile.getInputStream(src)) {