【问题标题】:Java emulation of MySQL COMRESS DECOMPRESS functionsMySQL COMRESS DECOMPRESS 函数的 Java 仿真
【发布时间】:2016-09-13 01:21:31
【问题描述】:

我想在 mysql VARBINARY 列中插入一些字节数据。数据很大,所以我想以压缩的方式存储它。

我正在使用 Percona 5.6 Mysql。我想在Java中模拟mysql的COMPRESS函数,然后将结果插入数据库。 我想使用 MySql DECOMPRESS 函数来访问这些数据。 有没有办法做到这一点?

我尝试过使用标准的 java.zip 包。但它不起作用。

编辑。换句话说,PHP 的 gzcompress (ZLIB) 的 Java 等价物是什么?

【问题讨论】:

  • 你的意思是它不起作用
  • 添加一些内容以帮助发现答案。
  • 为什么?让数据库来做。这就是它的用途。

标签: java mysql compression percona


【解决方案1】:

COMPRESS 的结果是一个 4 字节 little endian 长度的未压缩数据,后跟一个包含压缩数据的 zlib 流。

您可以使用Java 中的Deflater 类来压缩成zlib 流。在结果前面加上四字节长度。

【讨论】:

  • 谢谢马克。我缺少的部分是未压缩数据的四字节长度以小端格式存储。效果很好!
【解决方案2】:

解决方案:实现MYSQL Compress和DECOMPRESS

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

【讨论】:

    猜你喜欢
    • 2012-07-03
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多