我想将一些字节数据插入到mysql VARBINARY列中。数据很大,所以我想以压缩的方式存储它。
我正在使用Percona 5.6 Mysql。我想在Java中模拟mysql的COMPRESS函数,然后将结果插入数据库中。 我想使用MySql DECOMPRESS函数来访问这些数据。 有办法吗?
我尝试使用标准的java.zip包。但它不起作用。
修改即可。换句话说,PHP的gzcompress
(ZLIB)的Java等价物是什么?
答案 0 :(得分:2)
COMPRESS的结果是未压缩数据的四字节小端长度,后跟包含压缩数据的zlib流。
您可以使用Java中的Deflater
类来压缩到zlib流。以四字节长度表示结果。
答案 1 :(得分:1)
解决方案:实施MYSQL压缩和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);
}