2016-09-13 3 views
1

いくつかのバイトデータをmysql VARBINARYカラムに挿入したいと思います。データが大きいので、圧縮された形で保存したい。MySQL COMRESS DECOMPRESS関数のJavaエミュレーション

私はPercona 5.6 Mysqlを使用しています。私はJavaでMySQLのCOMPRESS関数をエミュレートし、その結果をデータベースに挿入したいと思います。 このデータにアクセスするために、私はDECOMPRESS関数を使用したいと思います。 これを行う方法はありますか?

私は標準のjava.zipパッケージを使用しようとしました。それは動作しません。

を編集します。言い換えれば、PHPのgzcompress(ZLIB)に相当するJavaは何ですか?

+0

を解凍? – Prisoner

+0

答えを見つけるのに役立つ情報を追加します。 –

+0

なぜですか?データベースにそれをさせてください。それがそれのためのものです。 – EJP

答えて

1

COMPRESSの結果は、圧縮されていないデータの4バイトのリトルエンディアンの長さで、その後に圧縮データを含むzlibストリームが続きます。

JavaでDeflaterクラスを使用すると、zlibストリームに圧縮できます。その結果に4バイトの長さを付けます。

+0

ありがとうございました。私の欠けている部分は、4バイト長の非圧縮データがリトルエンディアン形式で格納されていました。それは美しく働いた! – Cafebabe

0

ソリューション:MYSQL圧縮を実装し、あなたは_itがwork_しない何を意味

//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); 
    }