压缩php中的单词“ test”返回使用行“ eNorSS0uAQAEXQHB”
base64_encode(gzcompress(“ test”,9))
我也想要在Android应用中使用相同的方法。所以,我用下面的代码:
try {
byte[] input = "test".getBytes("UTF-8");
byte[] output = new byte[100];
Deflater compresser = new Deflater();
compresser.setInput(input);
compresser.finish();
compresser.deflate(output);
compresser.end();
return Base64.encodeToString(output, Base64.DEFAULT);
} catch (Exception e) {
return e.getMessage();
}
将输出作为
eJzLz0sFAAKRAUMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ==
尝试了以下另一种方法:
try {
ByteArrayOutputStream out = new ByteArrayOutputStream(str.length());
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();
byte[] compressedBytes = out.toByteArray();
return Base64.encodeToString(compressedBytes, Base64.DEFAULT); // I would return compressedBytes instead String
} catch (Exception e) {
return e.getMessage();
}
将输出作为
H4sIAAAAAAAAAMvPSwUA8YZsegMAAAA =
应该使用哪种方法从java(与php中一样)获取相同的压缩文件=> eNorSS0uAQAEXQHB
您的方法有两个问题。
compresser.deflate(output)
返回)这里是一个冗长的工作示例,用于在Java中生成与PHP代码段相同的Base64输出。
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.zip.Deflater;
public class CompressDemo {
public static void main(String[] args) throws Exception {
byte[] input = "test".getBytes(StandardCharsets.UTF_8);
byte[] buffer = new byte[100];
// create a deflater for the compression to best compression level (9)
Deflater compresser = new Deflater(Deflater.BEST_COMPRESSION);
compresser.setInput(input);
compresser.finish();
// keep the length of the compressed data
int compressedDataLength = compresser.deflate(buffer);
compresser.end();
// create an array only containing the compressed bytes
byte[] compressed = Arrays.copyOfRange(buffer, 0, compressedDataLength);
System.out.println(new String(Base64.getEncoder().encode(compressed)));
}
}