字节数组输出流,无需添加目的地,因为数据会被自动输入内存的缓冲区,需通过
.toByteArray()或.toString()拿到数据
因为需要使用子类ByteArrayOutputStream的新方法,所以不能写父类OutputStream对象
ByteArrayOutputStream os=new ByteArrayOutputStream();

因为数据写入了缓冲区,所以需要通过.toByteArray()和.toString()手动拿取

步骤:
创建目的地字节数组(用来存放从缓冲区拿来的数据): Byte[] last=null;
选择流: ByteArrayOutputStream os;
编码:字符串到字节
操作:os.write(byte[],0,byte,length)写入
获取数据:last=os.toByteArray();
System.out.println(new String(last,0,last.length)//或last.length可替换成os.size()
解码

public class test{ public static void main(String[]args) { //创建目的地 byte[] last=null; //选择流(新增方法) ByteArrayOutputStream os=null; //不用OutputStream,是因为要用子类ByteArrayOutputStream的新增方法 try { os =new ByteArrayOutputStream(); String s="hello world"; byte[] data=s.getBytes(); //编码,字符串到字符数组 os.write(data,0,data.length); os.flush(); //获取数据 last=os.toByteArray(); System.out.println(last.length); System.out.println(last.length+"---"+new String(last,0,last.length));//或者os.size() }catch(IOException e) { e.printStackTrace(); }}

}