开发者

Zip files based on InputStreams

I have a method to zip files in 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;
        t开发者_如何学编程ry {
            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);
    }
}

As you can see parameter inputFiles is an Array of File objects. This all works, but I'd like to have instead a collection of InputStream objects as parameter to make it more flexible.

But then I have the problem that when making a new ZipEntry (as in code above)

ZipEntry entry = new ZipEntry(f.getName());

I don't have a filename to give as parameter.

How should i solve this? Maybe a Map with (fileName,inputStream) pairs?

Any thoughts on this are appreciated!

Thanks, Nathan


I think your suggestion Map<String, InputStream> is a good solution.

Just a side note: Remember to close the inputstreams after you are done


If you want to make it more "fancy" you can always use create an interface:

interface ZipOuputInterface {
    String getName();
    InputStream getInputStream();
}

And have it implemented differently in your different cases for instance File:

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);
    }
}


I think that map is good. Just pay attention on the type ofmap you are using if you wish to preserve the original order of files in your ZIP. In this case use LinkedHashMap.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜