【问题标题】:How to create a Gzip archive in java, from strings?如何在 Java 中从字符串创建 Gzip 存档?
【发布时间】:2013-04-26 19:12:33
【问题描述】:

我有 3 个字符串,每个字符串代表一个txt 文件内容,不是从计算机加载的,而是由Java 生成的。

String firstFileCon = "firstContent"; //File in .gz: 1.txt
String secondFileCon = "secondContent"; //File in .gz: 2.txt
String thirdFileCon = "thirdContent"; //File in .gz: 3.txt

如何创建一个包含三个文件的GZIP 文件,并将压缩文件保存到光盘?

【问题讨论】:

  • 字符串是否包含您要压缩的文件的文件名,或者您想自己压缩字符串?

标签: java compression zip gzip


【解决方案1】:

创建一个名为 output.zip 的压缩文件,其中包含文件 1.txt2.txt3 .txt 及其内容字符串,请尝试以下操作:

Map<String, String> entries = new HashMap<String, String>();
entries.put("firstContent", "1.txt");
entries.put("secondContent", "2.txt");
entries.put("thirdContent", "3.txt");

FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
    fos = new FileOutputStream("output.zip");

    zos = new ZipOutputStream(fos);

    for (Map.Entry<String, String> mapEntry : entries.entrySet()) {
        ZipEntry entry = new ZipEntry(mapEntry.getValue()); // create a new zip file entry with name, e.g. "1.txt"
        entry.setMethod(ZipEntry.DEFLATED); // set the compression method
        zos.putNextEntry(entry); // add the ZipEntry to the ZipOutputStream
        zos.write(mapEntry.getKey().getBytes()); // write the ZipEntry content
    }
} catch (FileNotFoundException e) {
    // do something
} catch (IOException e) {
    // do something
} finally {
    if (zos != null) {
        zos.close();
    }
}

请参阅Creating ZIP and JAR files 了解更多信息,尤其是压缩文件一章。

【讨论】:

    【解决方案2】:

    一般来说GZIP只用于压缩单个文件(所以java.util.zip.GZIPOutputStream实际上只支持单个入口)。

    对于多个文件,我建议使用为多个文件设计的格式(如 zip)。 java.util.zip.ZipOutputStream 提供了这一点。如果出于某种原因,您确实希望最终结果是 GZIP,您始终可以创建一个包含所有 3 个文件的 ZIP 文件,然后将其 GZIP。

    【讨论】:

      【解决方案3】:

      目前尚不清楚您是否只想存储文本或实际的单个文件。我不认为您可以在没有先 TARing 的情况下将多个文件存储在 GZIP 中。这是一个将字符串存储到 GZIP 的示例。也许它会帮助你:

      public static void main(String[] args) {
          GZIPOutputStream gos = null;
      
          try {
              String str = "some string here...";
              File myGzipFile = new File("myFile.gzip");
      
              InputStream is = new ByteArrayInputStream(str.getBytes());
              gos = new GZIPOutputStream(new FileOutputStream(myGzipFile));
      
              byte[] buffer = new byte[1024];
              int len;
              while ((len = is.read(buffer)) != -1) {
                  gos.write(buffer, 0, len);
              }
          } catch (IOException e) {
              e.printStackTrace();
          } finally {
              try { gos.close(); } catch (IOException e) { }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-09
        • 2016-01-20
        • 2020-10-25
        • 1970-01-01
        • 2023-03-10
        • 2011-06-27
        • 2012-01-18
        相关资源
        最近更新 更多