5

我正在尝试压缩在字符串上转换的 Xml 列表,将它们仅保存在一个 zip 文件中,并作为 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;
}

任何人都可以帮助我吗?

4

1 回答 1

0

要测试您的 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

于 2017-03-23T16:52:30.013 回答