Reputation: 521
I am trying to output data through ZipOutputStream, but the resulting file is not compressed. This is under Windows 7. Here is an example:
import java.io.*;
import java.nio.file.*;
import java.util.Random;
import java.util.zip.*;
public class Testy {
public static void main(String[] args) {
byte[] data = new byte[100];
Random rnd = new Random(System.currentTimeMillis());
try {
BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(
Paths.get("record.zip"), StandardOpenOption.CREATE, StandardOpenOption.APPEND), 200000);
ZipOutputStream zout = new ZipOutputStream(out);
zout.setLevel(4);
zout.putNextEntry(new ZipEntry("record.dat"));
for (int i = 0; i < 10000; i++) {
rnd.nextBytes(data);
zout.write(data, 0, data.length);
Thread.sleep(1L);
}
zout.closeEntry();
zout.finish();
zout.close();
} catch (IOException | InterruptedException e) {
e.printStackTrace(System.out);
}
}
}
thanks for any help
Upvotes: 1
Views: 619
Reputation: 111219
Compression works by encoding repeated and predictable patterns in the input with shorter byte sequences. A completely random input, like you have here, has no predictable patterns, and cannot be compressed. The same would happen if you compressed a file that had already been compressed.
Try generating random upper case characters, random English words, or a random DNA sequence (letters A C T G) instead of random bytes, and you will see how well they are compressed.
Upvotes: 3