Java 基于InputStreams的Zip文件

Java 基于InputStreams的Zip文件,java,zip,inputstream,Java,Zip,Inputstream,我有一种用Java压缩文件的方法: public void compress(File[] inputFiles, OutputStream outputStream) { Validate.notNull(inputFiles, "Input files are required"); Validate.notNull(outputStream, "Output stream is required"); int BUFFER = 2048; Buffer

我有一种用Java压缩文件的方法:

public void compress(File[] inputFiles, OutputStream outputStream) {

    Validate.notNull(inputFiles, "Input files are required");
    Validate.notNull(outputStream, "Output stream is required");

    int BUFFER = 2048;

    BufferedInputStream origin = null;

    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(outputStream));
    byte data[] = new byte[BUFFER];

    for (File f : inputFiles) {
        FileInputStream fi;
        try {
            fi = new FileInputStream(f);
        } catch (FileNotFoundException e) {
            throw new RuntimeException("Input file not found", e);
        }
        origin = new BufferedInputStream(fi, BUFFER);
        ZipEntry entry = new ZipEntry(f.getName());
        try {
            out.putNextEntry(entry);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        int count;
        try {
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            origin.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    try {
        out.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
如您所见,参数inputFiles是一个文件对象数组。这一切都是可行的,但我希望有一个InputStream对象集合作为参数,以使其更灵活

但是我有一个问题,当制作一个新的ZipEntry时(如上面的代码所示)

我没有一个文件名作为参数

我应该如何解决这个问题?可能是带有(文件名、输入流)对的映射

如果您对此有任何想法,我们将不胜感激

谢谢,
内森

我认为你的建议
Map
是一个很好的解决方案

只是一个旁注:记住在完成后关闭inputstreams


如果您想让它更“别致”,您可以始终使用创建接口:

interface ZipOuputInterface {
    String getName();
    InputStream getInputStream();
}
并在不同的情况下以不同的方式实施,例如实例文件:

class FileZipOutputInterface implements ZipOutputInterface {

    File file;

    public FileZipOutputInterface(File file) {
        this.file = file;
    }

    public String getName() {
        return file.getAbstractName();
    }
    public InputStream getInputStream() {
        return new FileInputStream(file);
    }
}

我认为那张地图很好。如果您希望保留ZIP中文件的原始顺序,只需注意正在使用的映射类型。在这种情况下,请使用LinkedHashMap

class FileZipOutputInterface implements ZipOutputInterface {

    File file;

    public FileZipOutputInterface(File file) {
        this.file = file;
    }

    public String getName() {
        return file.getAbstractName();
    }
    public InputStream getInputStream() {
        return new FileInputStream(file);
    }
}