java 和 python base64压缩和解压缩
java
package com.example;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Base64OutputStream;
import org.apache.commons.lang.StringUtils;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class Base64zip {
public static final int ZIP_BUFFER_SIZE = 8192;
public static final String XML_ENCODING = "UTF-8";
public static String decodeBase64ZippedString(String loggingString64) throws IOException {
if (loggingString64 == null || loggingString64.isEmpty()) {
return "";
}
StringWriter writer = new StringWriter();
byte[] bytes64 = Base64.decodeBase64(loggingString64.getBytes());
ByteArrayInputStream zip = new ByteArrayInputStream(bytes64);
try (GZIPInputStream unzip = new GZIPInputStream(zip, Base64zip.ZIP_BUFFER_SIZE); BufferedInputStream in = new BufferedInputStream(unzip, Base64zip.ZIP_BUFFER_SIZE); InputStreamReader reader = new InputStreamReader(in, Base64zip.XML_ENCODING)) {
char[] buff = new char[Base64zip.ZIP_BUFFER_SIZE];
for (int length; (length = reader.read(buff)) > 0; ) {
writer.write(buff, 0, length);
}
}
return writer.toString();
}
public static String encodeBase64ZippedString(String in) throws IOException {
Charset charset = Charset.forName(Base64zip.XML_ENCODING);
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
try (Base64OutputStream base64OutputStream = new Base64OutputStream(baos); GZIPOutputStream gzos = new GZIPOutputStream(base64OutputStream)) {
gzos.write(in.getBytes(charset));
}
return baos.toString();
}
}
python
import base64
import gzip
import io
def decode_base64_zipped_string(logging_string64):
if not logging_string64:
return ""
bytes64 = base64.b64decode(logging_string64)
with io.BytesIO(bytes64) as zip_data:
with gzip.GzipFile(fileobj=zip_data, mode='rb') as unzip:
with io.TextIOWrapper(unzip, encoding='utf-8') as reader:
writer = io.StringIO()
buff = reader.read(4096)
while buff:
writer.write(buff)
buff = reader.read(4096)
return writer.getvalue()
def encode_string_to_base64_zipped(s):
with io.BytesIO() as buffer:
with gzip.GzipFile(mode='wb', fileobj=buffer) as zip_file:
zip_file.write(s.encode('utf-8'))
# Get compressed and Base64-encoded string
compressed = buffer.getvalue()
b64_encoded = base64.b64encode(compressed)
return b64_encoded.decode('utf-8')
本文来自博客园,作者:vx_guanchaoguo0,转载请注明原文链接:https://www.cnblogs.com/guanchaoguo/p/17434861.html

浙公网安备 33010602011771号