import java.io.*; import java.lang.reflect.Method; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import org.apache.commons.lang3.ArrayUtils; public class fileTest { public static final String GZIP_ENCODE_UTF_8 = "UTF-8"; public static byte[] compress(String str) { return compress(str, GZIP_ENCODE_UTF_8); } public static byte[] compress(String str, String encoding) { if (str == null || str.length() == 0) { return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip; try { gzip = new GZIPOutputStream(out); gzip.write(str.getBytes(encoding)); gzip.close(); } catch (IOException e) { System.out.println("gzip uncompress error."+e); } return out.toByteArray(); } public static byte[] getGzipBytesByFile(String pathStr) { File file = new File(pathStr); try { FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); byte[] b = new byte[1000]; int n; while ((n = fis.read(b)) != -1) { bos.write(b, 0, n); } fis.close(); ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(out); gzip.write(bos.toByteArray()); gzip.close(); return out.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; } public static byte[] unGzip(byte[] bytes) throws Exception{ java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); java.io.ByteArrayInputStream in = new java.io.ByteArrayInputStream(bytes); java.util.zip.GZIPInputStream ungzip = new java.util.zip.GZIPInputStream(in); byte[] buffer = new byte[256]; int n; while ((n = ungzip.read(buffer)) >= 0) out.write(buffer, 0, n); return out.toByteArray(); } public static void main(String args[]) throws Exception { byte[] fileBytes = getGzipBytesByFile("F:\\test.class"); String GzipBytes = ArrayUtils.toString(fileBytes); System.out.println(GzipBytes); System.out.println(unGzip(fileBytes)); } }