0
我試圖壓縮Strings
,將它們寫入文件(如Strings
)並解壓縮這些文件。 壓縮,我寫了這個功能:在Java中使用Snappy將字符串解壓縮爲字符串
public static String compress(String s) throws IOException {
byte[] by = Snappy.compress(s, StandardCharsets.UTF_8);
return new String(by, StandardCharsets.UTF_8);
}
,然後,爲解壓縮,
public static String uncompress(String s) throws IOException {
byte[] by = s.getBytes(StandardCharsets.UTF_8);
return Snappy.uncompressString(by, StandardCharsets.UTF_8);
}
,但我得到FAILED_TO_UNCOMPRESS(5)
,並通過查看數據,Snappy.compress(s, StandardCharsets.UTF_8)
不給結果爲相同將getBytes(StandardCharsets.UTF_8)
應用於使用我的compress
函數壓縮的數據。 你知道爲什麼嗎?我怎麼可以壓縮和解壓到Strings
?謝謝!
爲什麼你在'compress'方法中將結果存儲在'String'對象中?字符串不適合存儲任意字節。使'compress'方法返回'byte []'而不是'String',並使'uncompress'方法以'byte []'作爲參數而不是'String'。如果你真的需要將字節存儲在一個字符串中,那麼你將不得不使用諸如base64編碼之類的東西。 – Jesper