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;
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);
}
}
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:
And have it implemented differently in your different cases for instance File: