java中构造字节流的一种实现
import java.util.ArrayList;import java.util.List;/** * Created by kaven on 2018/4/2. */public class TestBytes { /** * 专门创建一个类来保存指定byte数 */ public class MyByte { byte[] data; MyByte(int n) { data = new byte[n]; } void setData(String s) { byte[] tmp = s.getBytes(); // 提示数据超了 if (tmp.length > data.length) { System.err.print("too many data"); } for (int i = 0; i < this.data.length && i < tmp.length; i++) { data[i] = tmp[i]; } } // 设置一个值到第一位 void setData(int i) { data[0] = (byte) i; } byte[] getByte() { return data; } int size() { return data.length; } } void login() { MyByte msgType = new MyByte(1); MyByte userId = new MyByte(16); MyByte msg = new MyByte(12); msgType.setData(1); userId.setData("1"); msg.setData("222"); Listlist = new ArrayList(); list.add(msgType); list.add(userId); list.add(msg); byte[] res = join(list); System.out.print(res.toString()); } /** * 将列表中的数据合并成一个数据 * @param list * @return */ private byte[] join(List list) { int count = 0; for (int i = 0; i < list.size(); i++) { count += list.get(i).size(); } byte[] res = new byte[count]; int start = 0; for (int i = 0; i < list.size(); i++) { byte[] tmp = list.get(i).getByte(); for (int j = 0; j < tmp.length; j++) { res[start] = tmp[j]; start += 1; } } return res; } public static void main(String args[]) { TestBytes a = new TestBytes(); a.login(); }}