ByteArrayOutputStream

ByteArrayInputStream: https://www.cnblogs.com/zhangj-ymm/p/9842657.html html

ByteArrayOutputStream是字節數組輸出流,它把數據寫入到本身的數組中,數組的大小會隨着數據的不斷增長而自動增加.數組

  1. 經過ByteArrayOutputStream()建立的"字節數組輸出流"對應的字節數組大小是32
  2. 經過ByteArrayOutputStream(int size)建立的"字節數組輸出流"對應的字節數組大小是size.
  3. write(int oneByte)的做用將int類型的oneByte換成byte類型,而後寫入到流中.
  4. write(byte[] buffer,int offset,int len)是將字節數組buffer寫入到流中,offset是從buffer中讀取數據的起始偏移量,len是讀取長度
  5. writeTo(OutputStream out)將數據寫到"輸出流out"中
public class ByteArrayOutputStreamTest {
    private static final int LEN = 5;
    // 對應英文字母「abcddefghijklmnopqrsttuvwxyz」
    private static final byte[] ArrayLetters = { 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C,
        0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A };

    public static void main(String[] args) {
    // 建立字節輸出流
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // 依次寫入「A」、「B」、「C」三個字母。0x41對應A,0x42對應B,0x43對應C,寫入到流中
    baos.write(0x41);
    baos.write(0x42);
    baos.write(0x43);
    System.out.printf("baos=%s\n", baos);
    // 將ArrayLetters數組中從「3」開始的後5個字節寫入到baos中。
    baos.write(ArrayLetters, 3, 5);
    System.out.printf("baos=%s\n", baos);
    }
}
// baos=ABC
// baos=ABCdefgh
相關文章
相關標籤/搜索