【问题标题】:Compressing(zip) List of files with ZipOutPutStream Java使用 ZipOutPutStream Java 压缩(zip)文件列表
【发布时间】:2017-08-16 07:54:33
【问题描述】:

我正在尝试压缩在字符串上转换的 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 文件?
  • 您使用的字符集是什么?因为字符串的长度并不总是与其字节数组的长度匹配。
  • @nandsito 不,我没有,ZipOutputStream 上有没有这个功能?
  • @Boschi 我正在处理字符集 UTF-8 上的 xml 列表作为字符串(这是列表 Map mapConvertedXml)。
  • 在方法结束时baos 将是一个内存中的 zip 文件。尝试将其转储到某个文件中

标签: java xml rest bytearrayoutputstream zipoutputstream


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多