I’m trying to make a program to compress file to .tar.gz:
Here is the code:
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
public class Compress {
public static void main(String[] args) {
BufferedInputStream input = null;
try {
input = new BufferedInputStream(new FileInputStream(new File("input_filename.filetype")));
TarArchiveOutputStream out = null;
try {
out = new TarArchiveOutputStream(new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream("output_filename.tar.gz"))));
out.putArchiveEntry(new TarArchiveEntry(new File("input_filename.filetype")));
int count;
byte data[] = new byte[input.available()];
while ((count = input.read(data)) != -1) {
out.write(data, 0, count);
}
input.close();
} catch (IOException ex) {
Logger.getLogger(Compress.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (out != null) {
try {
out.closeArchiveEntry();
out.close();
} catch (IOException ex) {
Logger.getLogger(Compress.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Compress.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
input.close();
} catch (IOException ex) {
Logger.getLogger(Compress.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
I’m using Apache Commons Compression as the library.
I test with 2 conditions:
- Compress GIF File
- Compress PDF File
And I compare compress using PeaZip, here is the result:
If the input file is GIF the size of the compress file increase, same if we using PeaZip. But for the other file it works for the compression process.
Can anyone explain what happen with this? Is there are something wrong with my code?
Thank you for your help…


Depending on what compression algorithm you’re using, you’ll get different results — each type of file compresses differently. Text files, for example, compress extremely well. Also, since GIF files are already compressed using LZW compression, a second compression should have little to no effect.
From Wikipedia, “GIF images are compressed using the Lempel-Ziv-Welch (LZW) lossless data compression technique to reduce the file size without degrading the visual quality.”
See http://en.wikipedia.org/wiki/Graphics_Interchange_Format for more info.