Compression (zip) List of files with ZipOutPutStream Java

I am trying to compress a list of Xml converted to Strings, store them in only one zip file, and return as a restful POST body. But every time I save the file, I get the error "The archive is in an unknown format or is corrupted."

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 this?

+3


source to share


1 answer


To check your zip file, save it temporarily to your filesystem and open it manually.

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

      

Then you can use something like this to create a Rest Rest server and get your file back.



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.

0


source







All Articles