Java实现读Chuck数据

之前列出了Chuck协议格式,现在做一个能读Chuck的代码:

public class IOLine {

	private byte[] data;
	
	private String line;

	public byte[] getData() {
		return data;
	}

	public void setData(byte[] data) {
		this.data = data;
	}

	public String getLine() {
		return line;
	}

	public void setLine(String line) {
		this.line = line;
	}
	
}

	public static byte[] readTrunck(InputStream is) throws Exception{
		ByteArrayOutputStream dos = null;
		dos = new ByteArrayOutputStream();
		try{
			DataInputStream dis = new DataInputStream(is);
			IOLine line = HttpUtil.readLine(is);
//			LogUtil.debug("line="+line.getLine());
			int len = HttpUtil.readDataLen(line);
			while(len>0){
				byte tmp[] = new byte[len];
				dis.readFully(tmp);
				dos.write(tmp);
				line = HttpUtil.readLine(is);
				if("".equals(line.getLine().trim())){
					line = HttpUtil.readLine(is);
				}
//				LogUtil.debug("line="+line.getLine());
				len = HttpUtil.readDataLen(line);
			}
			return dos.toByteArray();
		}finally{
			try{
				dos.close();
			}catch(Exception e){
				
			}
		}
	}


	/**
	 * 读一行
	 * @param is
	 * @return
	 * @throws Exception
	 */
	public static IOLine readLine(InputStream is) throws Exception{
		int b = 0;
		IOLine ret = new IOLine();
		byte[] data = new byte[MAX_DATA_SIZE];
		int k = 0;
		boolean f = false;
		boolean s = false;
		try{
			while( (b=is.read()) != -1){
				data[k++] = (byte) b;
				if('\r'== b){
					f = true;
				}
				else if(f && '\n' == b){
					s = true;
					break;
				}
				else{
					f = false;
				}
			}
		}catch(Exception e){}
		byte[] d = new byte[k];
		System.arraycopy(data, 0, d, 0, k);
		if(s){
			ret.setLine(new String(d));
		}
		ret.setData(d);
		return ret;
	}

当数据流读到数据区时,直接调用readTrunck方法,传入数据流,返回所有Chuck整合的字节数组。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值