简体   繁体   中英

Compressing(zip) List of files with ZipOutPutStream Java

I`m trying to compress a list of Xml converted on Strings, save them in only one zip file and returning as a body of a POST on restful. But everytime I save the file I get the error "The archive is either in unknown format or damaged".

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;
}

Can anyone help me with that?

To test your zip file please save it temporarily in your filesystem and open it manualy.

FileOutputStream fos = new FileOutputStream(pathToZipFile);
ZipOutputStream zos = new ZipOutputStream(fos);

Then, you can use something like that to construct your Rest Server and return your file.

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;
}

You can test this Advanced Rest Client for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM