How to use java.util.zip to archive / deflate strings in java for use in Google Earth?

Use case

I need to pack our kml, which is in String, in response to kmz for a network link in Google Earth. I would also like to wrap the badges and such while I am on it.

Problem

Using the implementation below, I get errors from both WinZip and Google Earth that are corrupted in the archive or that the file does not open. The part that differs from the other examples that I built are the lines in which the line is added:

ZipEntry kmlZipEntry = new ZipEntry("doc.kml");
out.putNextEntry(kmlZipEntry);
out.write(kml.getBytes("UTF-8"));

Please point me in the right direction to write the line correctly so that it is doc.xmlin the resulting kmz file. I know how to write a string to a temporary file, but I would really like to keep the operation in memory for understanding and efficiency.

    private static final int BUFFER = 2048;
    private static void kmz(OutputStream os, String kml)
    {
        try{
            BufferedInputStream origin = null;
            ZipOutputStream out = new ZipOutputStream(os);
            out.setMethod(ZipOutputStream.DEFLATED);
            byte data[] = new byte[BUFFER];
            File f = new File("./icons"); //folder containing icons and such
            String files[] = f.list();

            if(files != null)
            {
                for (String file: files) {
                    LOGGER.info("Adding to KMZ: "+ file);
                    FileInputStream fi = new FileInputStream(file);
                    origin = new BufferedInputStream(fi, BUFFER);
                    ZipEntry entry = new ZipEntry(file);
                    out.putNextEntry(entry);
                    int count;
                    while((count = origin.read(data, 0, BUFFER)) != -1) {
                        out.write(data, 0, count);
                    }
                    origin.close();
                }
            }
            ZipEntry kmlZipEntry = new ZipEntry("doc.kml");
            out.putNextEntry(kmlZipEntry);
            out.write(kml.getBytes("UTF-8"));
        }
        catch(Exception e)
        {
            LOGGER.error("Problem creating kmz file", e);
        }
    }

Bonus points for showing me how to put additional files from a folder iconsinto a similar folder in the archive, and not at the same level as doc.kml.

Update Even when saving a line in a temporary file, errors occur. Ugh.

Use case note . The use case is intended for use in a web application, but the code to get a list of files does not work there. See how-to-access-local-files-on-server-in-jboss-application for more details.

+3
1

close() ZipOutputStream. - finally try, .


. , .

ZipEntry entry = new ZipEntry("icons/" + file);
+4

Source: https://habr.com/ru/post/1753890/


All Articles