【发布时间】:2018-11-25 16:29:08
【问题描述】:
我正在尝试从生产者和消费者环境中压缩和解压缩字符串(它只接受字符串作为参数)。
所以在我压缩一个字符串之后,我将压缩的字节数组转换为字符串,然后将它传递给生产者。 然后在消费者部分,我将字符串取回,转换为字节数组,然后从字节中解压缩字符串。
如果我使用 byte[] 而不是转换成字符串,那么它工作正常。但我需要的是转换成字符串,反之亦然。
这是我的代码:
public class Compression {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
String strToCompress = "Helloo!! ";
byte[] compressedBytes = compress(strToCompress);
String compressedStr = new String(compressedBytes, StandardCharsets.UTF_8);
byte[] bytesToDecompress = compressedStr.getBytes(StandardCharsets.UTF_8);
String decompressedStr = decompress(bytesToDecompress);
System.out.println("Compressed Bytes : "+Arrays.toString(compressedBytes));
System.out.println("Decompressed String : "+decompressedStr);
}
public static byte[] compress(final String str) throws IOException {
if ((str == null) || (str.length() == 0)) {
return null;
}
ByteArrayOutputStream obj = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(obj);
gzip.write(str.getBytes("UTF-8"));
gzip.flush();
gzip.close();
return obj.toByteArray();
}
public static String decompress(final byte[] compressed) throws IOException {
final StringBuilder outStr = new StringBuilder();
if ((compressed == null) || (compressed.length == 0)) {
return "";
}
if (isCompressed(compressed)) { //It is not going into this if part
final GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(compressed));
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
String line;
while ((line = bufferedReader.readLine()) != null) {
outStr.append(line);
}
} else {
outStr.append(compressed);
}
return outStr.toString();
}
public static boolean isCompressed(final byte[] compressed) {
return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
}
}
【问题讨论】:
-
那么问题出在哪里? (你期望什么与发生什么)
-
消费者和生产者运行在不同的虚拟机上吗?他们如何沟通?通过网络还是通过管道在同一台机器上?
-
我删除了 Kafka 标签,但 Kafka 可以接受字节,而不仅仅是字符串。此外,它可以作为 Producer API 的一部分为您执行压缩
-
@isnot2bad 转换成压缩字符串后,我无法从compressedString.getBytes[] 中将它从compressedString 解压回来。它将 isCompressed 设为 false。
标签: java compression