[英]Zip files based on InputStreams
我有一個用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();
}
並且在不同的情況下以不同的方式實現它,例如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);
}
}
我認為地圖很好。 如果您希望保留ZIP中文件的原始順序,請注意您正在使用的地圖類型。 在這種情況下使用LinkedHashMap。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.