使用 Java 创建的 ZIP 文件在使用 Windows 资源管理器打开时显示为空

Sri*_*har 4 java zip

下面的代码用于压缩普通文本文件。当我使用 WinRaR 提取时,它正确显示内容,但当我使用 Windows 资源管理器打开时,它是空的,没有列出文件。我使用的是 Windows 7 Enterprise(64 位)操作系统。知道为什么它没有列在 Windows 资源管理器中吗?提前致谢。

File file = new File("F:\\sample.txt");
    byte[] buf = new byte[1024];
    String outFilename = "F:\\zipped_sample.zip";
    try {
      ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
      FileInputStream in = new FileInputStream(file);
      out.putNextEntry(new ZipEntry(file.toString()));
      int len;
      while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
        out.flush();
      }
      out.closeEntry();
      out.close();
      in.close();
    } catch (Exception e) {
      // log exception here
    }
Run Code Online (Sandbox Code Playgroud)

web*_*per 5

ZipEntry 构造函数采用名称,但您通过执行 file.toString(); 为其提供路径 尝试:

New ZipEntry(file.getName());
Run Code Online (Sandbox Code Playgroud)

这将传递文件名。