android压缩字符串,如何使用与.Net兼容的GZIPOutputStream压缩和解压缩字符串?

GZIP方法:

public static byte[] compress(String string) throws IOException {

ByteArrayOutputStream os = new ByteArrayOutputStream(string.length());

GZIPOutputStream gos = new GZIPOutputStream(os);

gos.write(string.getBytes());

gos.close();

byte[] compressed = os.toByteArray();

os.close();

return compressed;

}

public static String decompress(byte[] compressed) throws IOException {

final int BUFFER_SIZE = 32;

ByteArrayInputStream is = new ByteArrayInputStream(compressed);

GZIPInputStream gis = new GZIPInputStream(is, BUFFER_SIZE);

StringBuilder string = new StringBuilder();

byte[] data = new byte[BUFFER_SIZE];

int bytesRead;

while ((bytesRead = gis.read(data)) != -1) {

string.append(new String(data, 0, bytesRead));

}

gis.close();

is.close();

return string.toString();

}

并测试:

final String text = "hello";

try {

byte[] compressed = compress(text);

for (byte character : compressed) {

Log.d("test", String.valueOf(character));

}

String decompressed = decompress(compressed);

Log.d("test", decompressed);

} catch (IOException e) {

e.printStackTrace();

}

===更新===

如果你需要.Net兼容性,我的代码必须改变一点:

public static byte[] compress(String string) throws IOException {

byte[] blockcopy = ByteBuffer

.allocate(4)

.order(java.nio.ByteOrder.LITTLE_ENDIAN)

.putInt(string.length())

.array();

ByteArrayOutputStream os = new ByteArrayOutputStream(string.length());

GZIPOutputStream gos = new GZIPOutputStream(os);

gos.write(string.getBytes());

gos.close();

os.close();

byte[] compressed = new byte[4 + os.toByteArray().length];

System.arraycopy(blockcopy, 0, compressed, 0, 4);

System.arraycopy(os.toByteArray(), 0, compressed, 4, os.toByteArray().length);

return compressed;

}

public static String decompress(byte[] compressed) throws IOException {

final int BUFFER_SIZE = 32;

ByteArrayInputStream is = new ByteArrayInputStream(compressed, 4, compressed.length - 4);

GZIPInputStream gis = new GZIPInputStream(is, BUFFER_SIZE);

StringBuilder string = new StringBuilder();

byte[] data = new byte[BUFFER_SIZE];

int bytesRead;

while ((bytesRead = gis.read(data)) != -1) {

string.append(new String(data, 0, bytesRead));

}

gis.close();

is.close();

return string.toString();

}

您可以使用相同的测试脚本。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值