2016-09-13 4 views
1

mysql VARBINARY 컬럼에 바이트 데이터를 삽입하고 싶습니다. 데이터가 커서 압축 된 방식으로 저장하려고합니다.MySQL COMRESS DECOMPRESS 함수의 Java 에뮬레이션

저는 Percona 5.6 Mysql을 사용하고 있습니다. Java에서 MySQL의 COMPRESS 함수를 에뮬레이션하고 결과를 데이터베이스에 삽입하고 싶습니다. 이 데이터에 액세스하려면 MySQL DECOMPRESS 함수를 사용하고 싶습니다. 할 방법이 있습니까?

표준 java.zip 패키지를 사용해 보았습니다. 하지만 작동하지 않습니다.

을 편집하십시오. PHP의 gzcompress (ZLIB)에 해당하는 자바는 무엇이 다른가요?

+0

뭘 _it을 의미 WORK_하지 않는 압축 해제? – Prisoner

+0

답변을 찾을 수 있도록 무언가를 추가하십시오. –

+0

왜? 데이터베이스가 그렇게하도록하십시오. 그것이 바로 그 때문입니다. – EJP

답변

1

COMPRESS의 결과는 압축되지 않은 데이터의 4 바이트 리틀 엔디안 길이이며 압축 된 데이터가 포함 된 zlib 스트림이 뒤 따른다.

Java에서 Deflater 클래스를 사용하여 zlib 스트림으로 압축 할 수 있습니다. 그 결과 앞에 4 바이트 길이를 붙이십시오.

+0

감사 마크. 내 누락 된 부분은 4 바이트 길이의 비 압축 데이터가 리틀 엔디안 형식으로 저장되었습니다. 그것은 아름답게 일했다! – Cafebabe

0

솔루션 : MYSQL 압축 구현 및

//Compress byte stream using ZLib compression 
    public static byte[] compressZLib(byte[] data) { 
    Deflater deflater = new Deflater(); 
    deflater.setInput(data); 
    deflater.finish(); 

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); 
    byte[] buffer = new byte[1024]; 
    while (!deflater.finished()) { 
     int count = deflater.deflate(buffer); // returns the generated code... index 
     outputStream.write(buffer, 0, count); 
    } 
    try { 
     outputStream.close(); 
    } catch (IOException e) { 
    } 
    return outputStream.toByteArray(); 
    } 

//MYSQL COMPRESS. 
    public static byte[] compressMySQL(byte[] data) { 
    byte[] lengthBeforeCompression = ByteBuffer.allocate(Integer.SIZE/Byte.SIZE).order(ByteOrder.LITTLE_ENDIAN).putInt(data.length).array(); 
    ByteArrayOutputStream resultStream = new ByteArrayOutputStream(); 
    try { 
     resultStream.write(lengthBeforeCompression); 
     resultStream.write(compressZLib(data)); 
     resultStream.close(); 
    } catch (IOException e) { 
    } 
    return resultStream.toByteArray(); 
    } 

//Decompress using ZLib 
    public static byte[] decompressZLib(byte[] data) { 
    Inflater inflater = new Inflater(); 
    inflater.setInput(data); 
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); 
    byte[] buffer = new byte[1024]; 
    try { 
     while (!inflater.finished()) { 
     int count = inflater.inflate(buffer); 
     outputStream.write(buffer, 0, count); 
     } 
     outputStream.close(); 
    }catch (IOException ioe) { 
    } catch (DataFormatException e) { 
    } 
    return outputStream.toByteArray(); 
    } 

    //MYSQL DECOMPRESS 
    public static byte[] decompressSQLCompression(byte[] input) { 
    //ignore first four bytes which denote length of uncompressed data. use rest of the array for decompression 
    byte[] data= Arrays.copyOfRange(input,4,input.length); 
    return decompressZLib(data); 
    }