我正在尝试使用 OutputStream
下载多个文件。我创建了一个 for 循环,循环遍历具有文件名的 Vector FileS
并下载它们。但只有第一个文件被下载。我的 Vector
的 FileZero.xml
为 0,FileOne.xml
为 1,并且仅下载 fileZero。请帮忙;这是我的代码
for (int x = 0; x < FileS.size(); x++) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[1024];
reportFile = rm.getClass().getResourceAsStream("/folder/" + FileS.elementAt(x));
try {
while ((nRead = reportFile.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
} catch (Exception e) {
e.printStackTrace();
}
buffer.flush();
byte[] byteArray = buffer.toByteArray();
try {
byte bytes[] = null;
bytes = byteArray;
response.setContentLength(bytes.length);
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "inline;filename=" + FileS.elementAt(x));
OutputStream out = response.getOutputStream();
out.write(bytes);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
此外,我尝试注释掉 out.flush()
和 out.close()
;但没有帮助。我尝试将 OutputStream
对象放在循环之外只是为了测试这也没有帮助。
最佳答案
关闭输出流(在第一次迭代时)然后尝试写入它(在第二次迭代时)当然是一个错误。
但是即使你注释掉 out.close() ,也会有一个问题:你用单个文件的长度设置了两次
Content-Length`,但是你输出了两个文件的内容,所以长度必须是各个长度的总和。
您似乎正在尝试在一个请求中下载这两个文件。唯一可靠的方法是将它们打包到一个存档中(如 ZIP 存档)并下载一个文件,请参阅此处:How to download multiple files with one HTTP request?
或者只是一一下载。
关于Java 输出流 : Download Multiple Files,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48966114/