有没有办法将文件附加到Java中具有不同名称的zip?

时间:2013-03-04 00:07:18

标签: java zip rename zipinputstream zipoutputstream

我想知道是否有一种方法,而不是仅仅添加文件到zip,以在添加文件时重命名文件。我知道写方法:

(while ((len = zin.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }

我在互联网上搜索过,但没有相关信息。是否有任何类es或Java方法? 我不想重命名然后添加它的唯一原因是因为我正在使用aux文件处理Windows。 我的整个代码是:

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) {
        String name = entry.getName();
        boolean notInFiles = true;
        for (File f : files) {
            if (f.getName().equals(name)) {
                notInFiles = false;
                break;
            }
        }
        if (notInFiles) {
            out.putNextEntry(new ZipEntry(name));
            int len;
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 17, len);
            }
        }
        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();

0 个答案:

没有答案
相关问题