项目中要用到delphi 和 android 的数据传输,用delphi来压缩,在App里进行解压缩,用到的代码如下:
delphi:
procedure Zip(Input: TStream; Compress: Boolean);
const
MAXBUFSIZE = 1024 * 16; //16 KB
var
CS: TCompressionStream;
DS: TDecompressionStream;
Output: TStream;
Buf: array[0..MAXBUFSIZE - 1] of Byte;
BufSize: Integer;
begin
Output := TMemoryStream.Create;
if Assigned(Input) and Assigned(Output) then
begin
if Compress then // 压缩
begin
CS := TCompressionStream.Create(Output);
try
CS.CopyFrom(Input, 0); //从开始处复制
finally
CS.Free;
end;
end
else
begin // 解压
DS := TDecompressionStream.Create(Input);
try
BufSize := DS.Read(Buf, MAXBUFSIZE);
while BufSize > 0 do
begin
Output.Write(Buf, BufSize);
BufSize := DS.Read(Buf, MAXBUFSIZE);
end;
finally
DS.Free;
end;
end;
Input.Position := 0;
Input.Size := Output.Size;
Output.Position := 0;
Input.CopyFrom(Output, Output.Size);
Input.Position := 0;
end;
end;
Java:
public static byte[] decompress(InputStream is) {
InflaterInputStream iis = new InflaterInputStream(is);
ByteArrayOutputStream o = new ByteArrayOutputStream(1024);
try {
int i = 1024;
byte[] buf = new byte[i];
while ((i = iis.read(buf, 0, i)) > 0) {
o.write(buf, 0, i);
}
} catch (IOException e) {
e.printStackTrace();
}
return o.toByteArray();
}
}
使用过程中发现解压缩速度非常慢,后面进行研究后改进为:
public static byte[] decompress(InputStream is, OutputStream os) {
try {
InflaterInputStream iis = new InflaterInputStream(is);
BufferedInputStream bufferedInputStream = new BufferedInputStream(iis);
BufferedOutputStream o = new BufferedOutputStream(os);
try {
int i = 1024;
byte[] buf = new byte[i];
while ((i = bufferedInputStream.read(buf, 0, i)) > 0) {
o.write(buf, 0, i);
}
// return o.toByteArray();
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(o);
IOUtils.closeQuietly(bufferedInputStream);
IOUtils.closeQuietly(iis);
}
} catch (IOException e) {
// LOGGER.error("compress: ",e );
}
return null;
}
之前解压缩用时1秒左右,改进后8毫秒