Search code examples
javafilezipfileoutputstreamzipoutputstream

Create a File from a ZipOutputStream


I am using the below code to create a Zip file. I would like to return the created Zip as a File object in the method createZipFromFiles in order to use elsewhere. Can this be done from the FileOutputStream or ZipOutputStream?

public File createZipFromFiles(String zipName, List<File> files) {
    try {
        FileOutputStream fos = new FileOutputStream(zipName);
        ZipOutputStream zos = new ZipOutputStream(fos);
        for (File file : files) {
            addToZipFile(file.getName(), zos);
        }
        return null;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

public static void addToZipFile(String fileName, ZipOutputStream zos) throws FileNotFoundException, IOException {

    System.out.println("Writing '" + fileName + "' to zip file");

    File file = new File(fileName);
    FileInputStream fis = new FileInputStream(file);
    ZipEntry zipEntry = new ZipEntry(fileName);
    zos.putNextEntry(zipEntry);

    byte[] bytes = new byte[1024];
    int length;
    while ((length = fis.read(bytes)) >= 0) {
        zos.write(bytes, 0, length);
    }

    zos.closeEntry();
    fis.close();
}

Solution

  • Just return

    new File(zipName);
    

    since you already have the zip file name