【发布时间】:2019-04-10 08:20:09
【问题描述】:
我想将File 的数组压缩成一个压缩文件并将其发送到浏览器。每个File 的Inputstream 是一个shapefile,实际上由多个文件(.shp、.dbf、.shx、...)组成。
当我使用以下代码仅发送一个 File 时,它可以正常工作,并返回一个包含所有所需文件的 zipfile。
发送单个文件的代码
FileInputStream is = new FileInputStream(files.get(0));
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + getCurrentUser(request).getNiscode() + ".zip");
while (is.available() > 0) {
response.getOutputStream().write(is.read());
}
is.close();
if (response.getOutputStream() != null) {
response.getOutputStream().flush();
response.getOutputStream().close();
}
当我尝试将所有文件一起发送时,会返回一个包含所需文件夹的 zip 文件,但在每个文件夹中,只有一个带有 .file 扩展名的元素存在。它与ZipOutputStream的条目有关?
发送所有文件的代码
byte[] zip = this.zipFiles(files, Ids);
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename="test.zip");
response.getOutputStream().write(zip);
response.flushBuffer();
private byte[] zipFiles(ArrayList<File> files, String[] Ids) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
int count = 0;
for (File file : files) {
FileInputStream fis = new FileInputStream(file);
zos.putNextEntry(new ZipEntry(Ids[count] + "/"));
zos.putNextEntry(new ZipEntry(Ids[count] + "/" + file.getName()));
while (fis.available() > 0) {
zos.write(fis.read());
}
zos.closeEntry();
fis.close();
count ++;
}
zos.flush();
baos.flush();
zos.close();
baos.close();
return baos.toByteArray();
}
【问题讨论】:
-
尝试在文件名中添加文件扩展名:
file.getName() + ".zip"而不是file.getName() -
这已经指向了正确的方向。但是,使用
new ZipEntry(Ids[count] + "/")创建的每个文件夹现在都包含一个包含所需文件的 zip 文件夹。我只想要那里的文件,而不是在 zip 中编译。
标签: java inputstream zipoutputstream