首页 > 解决方案 > 使用 ZipOutputStream 将字符串写入 zip 文件

问题描述

最终目标只是压缩一个字符串并将其作为java中的字符串

 public void zip() {
    try {
      String myTestString = "a zip file test and another test";
      InputStream in = new ByteArrayInputStream(myTestString.getBytes());
      OutputStream out = new ByteArrayOutputStream();
      ZipOutputStream zipOut = new ZipOutputStream(out);
      ZipEntry zipEntry = new ZipEntry("wtf.txt");
      zipOut.putNextEntry(zipEntry);
      zipOut.write(myTestString.getBytes(),0,myTestString.getBytes().length);
      zipOut.close();
      myTestString = out.toString();
      out.close();
      System.out.println(myTestString);
      
    
      // just a test if I can read the file 
      in = new ByteArrayInputStream(myTestString.getBytes());
      out = new FileOutputStream("c:\\t\\string.zip");
      byte[] allBytes = new byte[(int) myTestString.getBytes().length];
      in.read(allBytes);
      out.write(allBytes);
      out.close();
      
      
    } catch (IOException e) {
      e.printStackTrace();
    }
    
  }

我发现我可以使用

  public void zipStringToFile2() {
    try {
      FileOutputStream fos = new FileOutputStream("c:/t/compressed.zip");
      ZipOutputStream zipOut = new ZipOutputStream(fos);
      String myTestString = "a zip file test and another test";
      int buffer = myTestString.getBytes().length;
//      byte[] myBytes = myTestString.getBytes();
      ByteArrayOutputStream out = new ByteArrayOutputStream(buffer);
      ZipEntry zipEntry = new ZipEntry("wtf.txt");
      zipOut.putNextEntry(zipEntry);
      zipOut.write(myTestString.getBytes(),0,buffer);
      zipOut.close();
      fos.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

但我无法将 zipOut 的输出写入字符串,然后将字符串写入文件,然后通过操作系统打开 zipfile。怎么可能呢?

标签: javazip

解决方案


myTestString = out.toString();

这不符合您的要求。字节不是字符串。toString() 没有提供有用的信息(它是一个调试工具)。保留字节数组 ( .toByteArray())。

out.close();

检索数据后关闭流?不要那样做。先关闭。(这并不重要,在这里。ByteArrayXStream 的 close() 根本不做任何事情。关键是,它要么什么都不做,在这种情况下你应该删除它,或者如果它确实有效果,你的代码会被破坏) .

myTestString.getBytes()

不,永远不要调用那个方法。它通过使用“平台默认编码”将字符解码为字节来为您提供字节。谁知道那是什么。

} catch (IOException e) {
    e.printStackTrace();
}

正确的“我不知道”异常处理程序是throw new RuntimeException("unhandled", e);,不是e.printStackTrace();。你得到更多的信息,你得到的 WTF 更少(因为即使事情显然是错误的,你也会继续执行,这是一个非常糟糕的主意)。

但我无法将 zipOut 的输出写入字符串

是的。字符串不是字节,你想要的根本不可能。任何语言。有些语言让它看起来像你可以 - 这些是糟糕的语言,将字符串和字节数组混为一谈。Python 决定崩溃并烧毁并发明一个全新的 python (python2k -> python3k) 来尝试解决这个问题,这表明了这一点。男孩那是一个巨大的痛苦,他们忍受它来解决这个疏忽。

但我无法将 zipOut 的输出写入字符串,然后将字符串写入文件,然后通过操作系统打开 zipfile。怎么可能呢?

因此,用“字节数组”替换该句子中所有出现的“字符串”,一切都很好!


推荐阅读