[JAVA][CLASS] ZipUtil.java - Compress Data and Decompress Data
import java.io.ByteArrayOutputStream;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class ZipUtil {
public static final int BUF_SIZE = 1024;
public static ZipUtil instance = null;
private ZipUtil() {
}
public static ZipUtil getInstance() {
if (instance == null)
instance = new ZipUtil();
return instance;
}
public byte[] compress(byte[] input) {
if (input == null)
return null;
byte[] buf = new byte[BUF_SIZE];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Deflater def = new Deflater();
def.setInput(input);
def.finish();
try {
while (!def.finished()) {
int count = def.deflate(buf);
baos.write(buf, 0, count);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
def.end();
}
return baos.toByteArray();
}
public byte[] decompress(byte[] input) {
if (input == null)
return null;
byte[] buf = new byte[BUF_SIZE];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Inflater inf = new Inflater();
inf.setInput(input);
try {
while (true) {
int count = inf.inflate(buf);
if (count > 0) {
baos.write(buf, 0, count);
} else if (count == 0 && inf.finished()) {
break;
} else {
throw new RuntimeException();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
inf.end();
}
return baos.toByteArray();
}
}