C++采用QT压缩加压方式,在数据传输过程中会导致乱码,JAVA与C++数据无法直接解压转换。压缩一方在压缩完成后,需要采用Base64进行encode编码;解压一方收到数据需要先采用Base64进行decode编码,然后解压。具体JAVA实现代码如下:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.zip.*;
public class ZipUtil {
/**
* 兼容C++ QT压缩方法 压缩
* @param source
* @return
*/
public static String zipQt(String source) {
Deflater deflater = new Deflater();
deflater.setInput(source.getBytes(StandardCharsets.UTF_8));
deflater.finish();
final byte[] bytes = new byte[1024];
try(ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);){
while (!deflater.finished()) {
//压缩输入数据并用压缩数据填充指定的缓冲区。
int length = deflater.deflate(bytes);
outputStream.write(bytes, 0, length);
}
deflater.end();
log.info("base64前:{}", outputStream.toString().length());
return Base64.getEncoder().encodeToString(outputStream.toByteArray());
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 兼容C++ QT压缩方法 解压
* @param source
* @return
*/
public static String unZipQt(String source) throws DataFormatException {
byte[] uncompressed = Base64.getDecoder().decode(source);
log.info("base64,{}", new String(uncompressed).length());
// byte[] uncompressed = source.getBytes(StandardCharsets.UTF_8);
final byte[] buffer = new byte[1024];
Inflater inflater = new Inflater();
inflater.setInput(uncompressed);
try(ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024)){
while (!inflater.finished()){
int length = inflater.inflate(buffer);
outputStream.write(buffer, 0, length);
}
return outputStream.toString();
}catch (Exception e){
e.printStackTrace();
}finally {
inflater.end();
}
return null;
}
}