user15204218
user15204218

Reputation:

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

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

my code is working.

I am new to java and would appreciate your help a lot. 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();
            }

Upvotes: 0

Views: 797

Answers (1)

Puce
Puce

Reputation: 38132

Since the text file is not zipped yet, don't use a ZipInputStream to read it. 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).

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.

Upvotes: 1

Related Questions