delphi Java zlib 通用和优化方法

项目中要用到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毫秒



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值