Java ByteArrayOutputStream class
Byte array output stream in memory to create a buffer byte array, all data sent to the output stream is stored in the byte array buffer. Create a byte array output stream objects There are several ways.
The following constructor creates a 32-byte (default size) buffer.
OutputStream bOut = new ByteArrayOutputStream();
Another constructor creates a buffer of size n bytes.
OutputStream bOut = new ByteArrayOutputStream(int a)
After the byte array output stream object is successfully created, you can see the following list of methods, convection write or other operations.
No. | Method Description |
---|---|
1 | public void reset () This byte array output stream count is reset to zero field, thus discarding the output stream all the data currently accumulated output. |
2 | public byte [] toByteArray () Creates a newly allocated byte array. Size of the array and the size of the current output stream, the content is a copy of the current output stream. |
3 | public String toString () The buffer's contents into a string, according to the platform's default character encoding bytes into characters. |
4 | public void write (int w) The specified byte to this byte array output stream. |
5 | public void write (byte [] b , int of, int len) The specified byte array starting at offset off beginning len bytes written to this byte array output stream. |
6 | public void writeTo (OutputStream outSt) All the contents of this byte array output stream to the specified output stream argument. |
Examples
The following example demonstrates the use of ByteArrayInputStream and ByteArrayOutputStream:
import java.io.*; public class ByteStreamTest { public static void main(String args[])throws IOException { ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12); while( bOutput.size()!= 10 ) { // 获取用户输入 bOutput.write(System.in.read()); } byte b [] = bOutput.toByteArray(); System.out.println("Print the content"); for(int x= 0 ; x < b.length; x++) { // 打印字符 System.out.print((char)b[x] + " "); } System.out.println(" "); int c; ByteArrayOutputStream bInput = new ByteArrayOutputStream(b); System.out.println("Converting characters to Upper case " ); for(int y = 0 ; y < 1; y++ ) { while(( c= bInput.read())!= -1) { System.out.println(Character.toUpperCase((char)c)); } bInput.reset(); } } }
The above examples compiled results are as follows:
asdfghjkly Print the content a s d f g h j k l y Converting characters to Upper case A S D F G H J K L Y