简体   繁体   English

为什么我的代码 ( ZipOutputStream ) 将空文件保存在 ZIP 中?

[英]Why does my code ( ZipOutputStream ) saves empty file in ZIP?

I have a simple code that is supposed to make txt file zipped, though txt file has some content, it's empty in a zip folder ( it has 89 bytes ( like buffer ) but all are just spaces. The interesting part is that if I write我有一个简单的代码,应该使 txt 文件压缩,虽然 txt 文件有一些内容,但它在 zip 文件夹中是空的(它有 89 个字节(如缓冲区)但都只是空格。有趣的部分是,如果我写

byte[] buffer = Files.readAllBytes(path); 

my code is working.我的代码正在运行。

I am new to java and would appreciate your help a lot.我是 java 的新手,非常感谢您的帮助。 Because I trully don't understand what I am doing wroing.因为我真的不明白我在做什么。

 public class Test {
        public static void main(String[] args) throws IOException {
            try (FileInputStream fis = new FileInputStream("C:\\Users\\10\\Desktop\\ds.txt");
                 ZipInputStream zis = new ZipInputStream(fis);
                 ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(Paths.get("C:\\Users\\10\\Desktop\\ds.zip")))) {
    
    
                byte[] buffer = new byte[fis.available()];
    
                zos.putNextEntry(new ZipEntry("ds.txt"));
    
                zis.read(buffer);
                zos.write(buffer);
                zos.closeEntry();
            }

Since the text file is not zipped yet, don't use a ZipInputStream to read it.由于文本文件还没有被压缩,所以不要使用 ZipInputStream 来读取它。 Just use the FileInputStream, or even better the NIO.2 File API (you're using it already to create the ZipOutputStream but not to create the InputStream).只需使用 FileInputStream,或者更好的是NIO.2 文件 API (您已经在使用它来创建 ZipOutputStream 但没有创建 InputStream)。

There is even a file system provider for the NIO.2 File API to read/ write to Zip files using the same API: https://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html (For Java 11+ the following module is required: https://docs.oracle.com/en/java/javase/11/docs/api/jdk.zipfs/module-summary.html ) There is even a file system provider for the NIO.2 File API to read/ write to Zip files using the same API: https://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/ zipfilesystemprovider.html (For Java 11+ the following module is required: https://docs.oracle.com/en/java/javase/11/docs/api/jdk.zipfs/module-summary.html )

Also make sure to use try-with-resources for the OutputStream as well, not just the InputStream, to properly close the stream in the finally block.还要确保对 OutputStream 使用 try-with-resources,而不仅仅是 InputStream,以正确关闭 finally 块中的 stream。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM