我有一个用 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 是一个 File 对象数组。这一切都有效,但我希望使用 InputStream 对象的集合作为参数,以使其更加灵活。
但是我遇到了一个问题,当创建一个新的 ZipEntry 时(如上面的代码)
ZipEntry entry = new ZipEntry(f.getName());
我没有文件名作为参数。
我该如何解决这个问题?也许是一个带有 (fileName,inputStream) 对的 Map?
任何对此的想法都值得赞赏!
谢谢, 内森
最佳答案
我认为你的建议Map<String, InputStream>
是一个很好的解决方案。
附注:完成后记得关闭输入流
<小时/>如果您想让它更加“花哨”,您可以随时使用创建界面:
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);
}
}
关于java - 基于InputStreams的Zip文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7334972/