java _io_ ByteArrayOutputStream

Byte array output stream, without adding a destination, because the data is automatically entered in the buffer memory, by the need
to get data .toByteArray () or .toString ()
because the new subclass ByteArrayOutputStream requires the use of, the parent can not write class OutputStream object
ByteArrayOutputStream os = new ByteArrayOutputStream ();

Since data is written to the buffer, it is necessary to manually pick up by .toByteArray () and .toString ()

Step:
Create a destination byte array (brought from the buffer used to store data): Byte [] last = null ;
selected stream: ByteArrayOutputStream os;
Code: byte string into
operation: os.write (byte [] , 0, byte, length) written to
acquire data: = os.toByteArray Last ();
System.out.println (new new String (Last, 0, last.length) // last.length or alternatively into os.size ( )
decoding

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();
    }

}

}

Guess you like

Origin blog.51cto.com/14437184/2423216