자바 byte array 압축방법

자바에서 byte arrary 데이터를 송수신할 때 데이터를 압축해서 통신하면 용량이 줄어들어서 조금 더 성능을 향상 시킬 수 있습니다.

자바 Deflater, Inflater 를 이용한 압축 및 압축풀기 방법

소스코드

import java.util.zip.Deflater; //압축
import java.util.zip.Inflater; //압축풀기

    @PostMapping(path="/CompressTest", consumes="application/json", produces="application/json")
    public void CompressTest(@RequestBody Map<String, String> vo)
    {
        String str = vo.get("str");
        byte[] byteArray = str.getBytes();
        System.out.println("bytelength: " + byteArray.length);
        
        byte[] compByteArray = byteCompress(byteArray);
        System.out.println("compBytelength: " + compByteArray.length);
        
        byte[] deCompByteArray = byteDecompress(compByteArray);
        System.out.println("deCompBytelength: " + deCompByteArray.length);
    }
    
    // 압축 Compress
    public static byte[] byteCompress(byte[] data) {
        byte[] returnByteArray = null;
        try {
            Deflater deflater = new Deflater();
            deflater.setLevel(Deflater.BEST_COMPRESSION);
            deflater.setInput(data);
            deflater.finish();
            
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(data.length);
            
            byte[] buffer = new byte[1024];
             
            while(!deflater.finished()) {
                byteArrayOutputStream.write(buffer, 0, deflater.deflate(buffer));
            }
             
            returnByteArray = byteArrayOutputStream.toByteArray();
         
            byteArrayOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
         
        return returnByteArray;
    }
    
    // 압축풀기 DeCompress
    public static byte[] byteDecompress(byte[] data) {
        byte[] returnByteArray = null;
        try {
            Inflater inflater = new Inflater();
            inflater.setInput(data);
             
            byte[] buffer = new byte[1024];
             
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(data.length);
            
            while(!inflater.finished()) {
                try {
                    int count = inflater.inflate(buffer);
                    byteArrayOutputStream.write(buffer, 0, count);
                } catch (DataFormatException e) {
                    e.printStackTrace();
                }
            }
             
            returnByteArray = byteArrayOutputStream.toByteArray();
         
            byteArrayOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
         
        return returnByteArray;
    }

대략 600byte 를 압축하면 약300byte 로 압축됩니다.