首页 > 编程 > Java > 正文

Java实现读Chuck数据

2019-11-11 06:09:39
字体:
来源:转载
供稿:网友

之前列出了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整合的字节数组。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表