【问题标题】:How to use java.util.zip to archive/deflate string in java for use in Google Earth?如何使用 java.util.zip 在 Java 中归档/压缩字符串以在 Google 地球中使用?
【发布时间】:2010-07-09 13:49:20
【问题描述】:

用例

我需要将字符串中的 kml 打包成 kmz 响应,用于 Google 地球中的网络链接。我还想在我做的时候把图标等包装起来。

问题

使用下面的实现,我收到来自 WinZip 和 Google Earth 的错误,即存档已损坏或文件无法分别打开。与我构建的其他示例不同的部分是添加字符串的行:

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

请指出正确的方向以正确写入字符串,使其位于生成的 kmz 文件中的 doc.xml 中。我知道如何将字符串写入临时文件,但为了便于理解和提高效率,我非常希望将操作保留在内存中。

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

向我展示了如何将补充文件从 icons 文件夹放入存档中的类似文件夹,而不是与 doc.kml 位于同一层。

更新 即使将字符串保存到临时文件,也会发生错误。呃。

用例说明 该用例用于网络应用程序,但获取文件列表的代码在该应用程序中不起作用。详情见how-to-access-local-files-on-server-in-jboss-application

【问题讨论】:

    标签: java zip kmz


    【解决方案1】:

    您忘记在ZipOutputStream 上致电close()。调用它的最佳位置是创建它的 try 块的 finally 块。


    更新:要创建文件夹,只需将其名称添加到条目名称中即可。

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

    【讨论】:

    • 酷,成功了!您不会碰巧没有如何包含目录结构吗?我希望目录中 icons 文件夹中的 for 循环中的文件位于 kmz/zip 结构中的 icons 文件夹中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    相关资源
    最近更新 更多