java - Zlib compression is too big in size -
i new java, have decided learn doing small project in it. need compress string using zlib , write file. however, file turn out big in size. here code example:
string input = "yasar\0yasar"; // test input. input have null character in it. byte[] compressed = new byte[100]; // hold compressed content deflater compresser = new deflater(); compresser.setinput(input.getbytes()); compresser.finish(); compresser.deflate(compressed); file test_file = new file(system.getproperty("user.dir"), "test_file"); try { if (!test_file.exists()) { test_file.createnewfile(); } try (fileoutputstream fos = new fileoutputstream(test_file)) { fos.write(compressed); } } catch (ioexception e) { e.printstacktrace(); }
this write 1 kilobytes file, while file should @ 11 bytes (because content 11 bytes here.). think problem in way initialize byte array compressed 100 bytes, don't know how big compreesed data in advance. doing wrong here? how can fix it?
if don't want write whole array , instead write part of filled deflater
use outputstream#write(byte[] array, int offset, int lenght)
roughly
string input = "yasar\0yasar"; // test input. input have null character in it. byte[] compressed = new byte[100]; // hold compressed content deflater compresser = new deflater(); compresser.setinput(input.getbytes()); compresser.finish(); int length = compresser.deflate(compressed); file test_file = new file(system.getproperty("user.dir"), "test_file"); try { if (!test_file.exists()) { test_file.createnewfile(); } try (fileoutputstream fos = new fileoutputstream(test_file)) { fos.write(compressed, 0, length); // starting @ 0th byte - lenght(-1) } } catch (ioexception e) { e.printstacktrace(); }
you still see 1kb
or in windows because see there seems either rounded (you wrote 100 bytes before) or refers size on filesystem @ least 1 block large (should 4kb iirc). rightclick file , check size in properties, should show actual size.
if don't know size in advance, don't use deflater
, use deflateroutputstream writes data of length compressed.
try (outputstream out = new deflateroutputstream(new fileoutputstream(test_file))) { out.write("hello!".getbytes()); }
above example use default values deflating can pass configured deflater
in constructor of deflateroutputstream
change behavior.
Comments
Post a Comment