我正在尝试压缩在字符串上转换的 Xml 列表,将它们保存在一个 zip 文件中,并在 restful 上作为 POST 的正文返回。但每次保存文件时,我都会收到错误消息“存档格式未知或已损坏”。
protected ByteArrayOutputStream zip(Map<String, String> mapConvertedXml) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
try {
for(Map.Entry<String, String> current : mapConvertedXml.entrySet()){
ZipEntry entry = new ZipEntry(current.getKey() + ".xml");
entry.setSize(current.getValue().length());
zos.putNextEntry(entry);
zos.write(current.getValue().getBytes());
zos.flush();
}
zos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return baos;
}
有人可以帮我吗?
最佳答案
要测试您的 zip 文件,请将其临时保存在您的文件系统中并手动打开。
FileOutputStream fos = new FileOutputStream(pathToZipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
然后,您可以使用类似的东西来构建您的 Rest Server 并返回您的文件。
public static Response getFileLast(@Context UriInfo ui, @Context HttpHeaders hh) {
Response response = null;
byte[] sucess = null;
ByteArrayOutputStream baos = getYourFile();
sucess = baos.toByteArray();
if(sucess!=null) {
response = Response.ok(sucess, MediaType.APPLICATION_OCTET_STREAM).header("content-disposition","attachment; filename = YourFileName").build();
} else {
response = Response.status(Status.NOT_FOUND).type(MediaType.APPLICATION_JSON).entity(new Error("Error downloading file.")).build();
}
return response;
}
你可以测试这个Advanced Rest Client例如。
关于java - 使用 ZipOutPutStream Java 压缩(zip)文件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42981503/