Adding (and overriding) files to compressed archiv

2019-09-09 19:50发布

问题:

Well, it is as simple as the title. I tried for many hours to make a method that will take the archive file and a File[] (the files that will be added to the archive) and I only made it to the point that the method adds new files into the archive, but if a file with the same name of a file that I'm trying to add already exists, it throws me an error. I tried searching for a solution but didn't find any. Can you help me make a method that will take two parameters: File archive, File[] fileToAdd. That will add files to an archive and if needed will override existing files? Thank you, TheRedCoder

Edit: Here is my current code

public static void addFilesToZip(File zipFile, File[] files) throws IOException {
    File tempFile = File.createTempFile(zipFile.getName(), null);
    tempFile.delete();
    boolean renameOk = zipFile.renameTo(tempFile);
    if (!renameOk) {
        throw new RuntimeException(
                "could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath());
    }
    byte[] buf = new byte[1024];
    ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
    ZipEntry entry = zin.getNextEntry();
    while (entry != null) {
        File file = null;
        String name = entry.getName();
        boolean notInFiles = true;
        for (File f : files) {
            if (f.getName().equals(name)) {
                notInFiles = false;
                file = f;
                break;
            }
        }
        if (notInFiles) {
            out.putNextEntry(new ZipEntry(name));
            int len;
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } else {
            /**
             *
             * I'm stuck here, what should i do here?
             * 
             */
        }
        entry = zin.getNextEntry();
    }
    zin.close();
    for (int i = 0; i < files.length; i++) {
        InputStream in = new FileInputStream(files[i]);
        out.putNextEntry(new ZipEntry(files[i].getName()));
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.closeEntry();
        in.close();
    }
    out.close();
    tempFile.delete();
}