![](/img/trans.png)
[英]compress a string in Python and how to decompress this string in java
[英]Compress and Decompress String in Java
我正在嘗試從生產者和使用者環境(僅接受字符串作為參數)壓縮和解壓縮字符串。
因此,在壓縮字符串之后,我將壓縮的字節數組轉換為字符串,然后將其傳遞給生產者。 然后在使用者部分,我將字符串取回,轉換為字節數組,然后從字節解壓縮字符串。
如果我使用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));
}
}
您不能假定壓縮字符串可以視為UTF-8,因為許多可能的字節組合都不是有效的UTF-8。 我建議嘗試使用ISO-8859-1,該方法將所有8位值保持未翻譯狀態。
還要注意,雖然大段文本應該變小,但小字符串可以變大。
注意:此循環將刪除所有換行符
String line;
while ((line = bufferedReader.readLine()) != null) {
outStr.append(line);
}
我建議改為使用不刪除任何字符的char[]
復制。
char[] chars = new char[512];
for(int len; (len = reader.read(chars)) > 0;)
outStr.append(chars, 0, len);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.