如何在Java中使用ByteArrayOutputStream

本篇文章給大家分享的是有關(guān)如何在Java中使用ByteArrayOutputStream,小編覺(jué)得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說(shuō),跟著小編一起來(lái)看看吧。

目前創(chuàng)新互聯(lián)建站已為數(shù)千家的企業(yè)提供了網(wǎng)站建設(shè)、域名、虛擬主機(jī)、網(wǎng)站托管、服務(wù)器租用、企業(yè)網(wǎng)站設(shè)計(jì)、肅寧網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶(hù)導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶(hù)和合作伙伴齊心協(xié)力一起成長(zhǎng),共同發(fā)展。

ByteArrayOutputStream 介紹

ByteArrayOutputStream 是字節(jié)數(shù)組輸出流。它繼承于OutputStream。

ByteArrayOutputStream 中的數(shù)據(jù)被寫(xiě)入一個(gè) byte 數(shù)組。緩沖區(qū)會(huì)隨著數(shù)據(jù)的不斷寫(xiě)入而自動(dòng)增長(zhǎng)??墒褂?toByteArray() 和 toString() 獲取數(shù)據(jù)。

OutputStream 函數(shù)列表

我們來(lái)看看ByteArrayOutputStream的父類(lèi)OutputStream的函數(shù)接口。

// 構(gòu)造函數(shù)
OutputStream()
     void  close()
     void  flush()
     void  write(byte[] buffer, int offset, int count)
     void  write(byte[] buffer)
abstract void  write(int oneByte)
ByteArrayOutputStream 函數(shù)列表
 // 構(gòu)造函數(shù)
ByteArrayOutputStream()
ByteArrayOutputStream(int size)
       void  close()
synchronized void  reset()
       int   size()
synchronized byte[] toByteArray()
       String toString(int hibyte)
       String toString(String charsetName)
       String toString()
synchronized void  write(byte[] buffer, int offset, int len)
synchronized void  write(int oneByte)
synchronized void  writeTo(OutputStream out)

OutputStream和ByteArrayOutputStream源碼分析

OutputStream是ByteArrayOutputStream的父類(lèi),我們先看看OutputStream的源碼,然后再學(xué)ByteArrayOutputStream的源碼。

1. OutputStream.java源碼分析(基于jdk1.7.40) 

package java.io;
 public abstract class OutputStream implements Closeable, Flushable {
   // 將字節(jié)b寫(xiě)入到“輸出流”中。
   // 它在子類(lèi)中實(shí)現(xiàn)!
   public abstract void write(int b) throws IOException;
   // 寫(xiě)入字節(jié)數(shù)組b到“字節(jié)數(shù)組輸出流”中。
   public void write(byte b[]) throws IOException {
    write(b, 0, b.length);
   }
   // 寫(xiě)入字節(jié)數(shù)組b到“字節(jié)數(shù)組輸出流”中,并且off是“數(shù)組b的起始位置”,len是寫(xiě)入的長(zhǎng)度
   public void write(byte b[], int off, int len) throws IOException {
     if (b == null) {
       throw new NullPointerException();
    } else if ((off < 0) || (off > b.length) || (len < 0) ||
          ((off + len) > b.length) || ((off + len) < 0)) {
      throw new IndexOutOfBoundsException();
     } else if (len == 0) {
      return;
     }
     for (int i = 0 ; i < len ; i++) {
      write(b[off + i]);
     }
   }
   public void flush() throws IOException {
   }
   public void close() throws IOException {
   }
 }

2. ByteArrayOutputStream 源碼分析(基于jdk1.7.40) 

 package java.io;
  import java.util.Arrays;
  public class ByteArrayOutputStream extends OutputStream {
    // 保存“字節(jié)數(shù)組輸出流”數(shù)據(jù)的數(shù)組
    protected byte buf[];
   // “字節(jié)數(shù)組輸出流”的計(jì)數(shù)
   protected int count;
   // 構(gòu)造函數(shù):默認(rèn)創(chuàng)建的字節(jié)數(shù)組大小是。
   public ByteArrayOutputStream() {
     this(32);
   }
   // 構(gòu)造函數(shù):創(chuàng)建指定數(shù)組大小的“字節(jié)數(shù)組輸出流”
   public ByteArrayOutputStream(int size) {
     if (size < 0) {
       throw new IllegalArgumentException("Negative initial size: "
                         + size);
     }
     buf = new byte[size];
   }
   // 確認(rèn)“容量”。
   // 若“實(shí)際容量 < minCapacity”,則增加“字節(jié)數(shù)組輸出流”的容量
   private void ensureCapacity(int minCapacity) {
     // overflow-conscious code
     if (minCapacity - buf.length > 0)
       grow(minCapacity);
   }
   // 增加“容量”。
   private void grow(int minCapacity) {
     int oldCapacity = buf.length;
     // “新容量”的初始化 = “舊容量”x2
     int newCapacity = oldCapacity << 1;
     // 比較“新容量”和“minCapacity”的大小,并選取其中較大的數(shù)為“新的容量”。
     if (newCapacity - minCapacity < 0)
      newCapacity = minCapacity;
     if (newCapacity < 0) {
       if (minCapacity < 0) // overflow
         throw new OutOfMemoryError();
       newCapacity = Integer.MAX_VALUE;
     }
     buf = Arrays.copyOf(buf, newCapacity);
   }
   // 寫(xiě)入一個(gè)字節(jié)b到“字節(jié)數(shù)組輸出流”中,并將計(jì)數(shù)+1
  public synchronized void write(int b) {
     ensureCapacity(count + 1);
     buf[count] = (byte) b;
     count += 1;
   }
   // 寫(xiě)入字節(jié)數(shù)組b到“字節(jié)數(shù)組輸出流”中。off是“寫(xiě)入字節(jié)數(shù)組b的起始位置”,len是寫(xiě)入的長(zhǎng)度
   public synchronized void write(byte b[], int off, int len) {
     if ((off < 0) || (off > b.length) || (len < 0) ||
       ((off + len) - b.length > 0)) {
       throw new IndexOutOfBoundsException();
     }
     ensureCapacity(count + len);
     System.arraycopy(b, off, buf, count, len);
     count += len;
   }
   // 寫(xiě)入輸出流outb到“字節(jié)數(shù)組輸出流”中。
   public synchronized void writeTo(OutputStream out) throws IOException {
     out.write(buf, 0, count);
   }
   // 重置“字節(jié)數(shù)組輸出流”的計(jì)數(shù)。
   public synchronized void reset() {
     count = 0;
   }
   // 將“字節(jié)數(shù)組輸出流”轉(zhuǎn)換成字節(jié)數(shù)組。
   public synchronized byte toByteArray()[] {
     return Arrays.copyOf(buf, count);
   }
   // 返回“字節(jié)數(shù)組輸出流”當(dāng)前計(jì)數(shù)值
   public synchronized int size() {
     return count;
   }
   public synchronized String toString() {
     return new String(buf, 0, count);
   }
  public synchronized String toString(String charsetName)
     throws UnsupportedEncodingException
   {
     return new String(buf, 0, count, charsetName);
   }
   @Deprecated
   public synchronized String toString(int hibyte) {
    return new String(buf, hibyte, 0, count);
   }
   public void close() throws IOException {
   }
 }

說(shuō)明:

ByteArrayOutputStream實(shí)際上是將字節(jié)數(shù)據(jù)寫(xiě)入到“字節(jié)數(shù)組”中去。

(01) 通過(guò)ByteArrayOutputStream()創(chuàng)建的“字節(jié)數(shù)組輸出流”對(duì)應(yīng)的字節(jié)數(shù)組大小是32。

(02) 通過(guò)ByteArrayOutputStream(int size) 創(chuàng)建“字節(jié)數(shù)組輸出流”,它對(duì)應(yīng)的字節(jié)數(shù)組大小是size。

(03) write(int oneByte)的作用將int類(lèi)型的oneByte換成byte類(lèi)型,然后寫(xiě)入到輸出流中。

(04) write(byte[] buffer, int offset, int len) 是將字節(jié)數(shù)組buffer寫(xiě)入到輸出流中,offset是從buffer中讀取數(shù)據(jù)的起始偏移位置,len是讀取的長(zhǎng)度。

(05) writeTo(OutputStream out) 將該“字節(jié)數(shù)組輸出流”的數(shù)據(jù)全部寫(xiě)入到“輸出流out”中。 

示例代碼

關(guān)于ByteArrayOutputStream中API的詳細(xì)用法,參考示例代碼(ByteArrayOutputStreamTest.java): 

 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.ByteArrayInputStream;
 /**
  * ByteArrayOutputStream 測(cè)試程序
  *
  * 
 */
 public class ByteArrayOutputStreamTest {
   private static final int LEN = 5;
   // 對(duì)應(yīng)英文字母“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) {
     //String tmp = new String(ArrayLetters);
     //System.out.println("ArrayLetters="+tmp);
     tesByteArrayOutputStream() ;
   }
   /**
   * ByteArrayOutputStream的API測(cè)試函數(shù)
   */
   private static void tesByteArrayOutputStream() {
     // 創(chuàng)建ByteArrayOutputStream字節(jié)流
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     // 依次寫(xiě)入“A”、“B”、“C”三個(gè)字母。0x41對(duì)應(yīng)A,0x42對(duì)應(yīng)B,0x43對(duì)應(yīng)C。
     baos.write(0x41);
     baos.write(0x42);
    baos.write(0x43);
    System.out.printf("baos=%s\n", baos);
    // 將ArrayLetters數(shù)組中從“3”開(kāi)始的后5個(gè)字節(jié)寫(xiě)入到baos中。
    // 即對(duì)應(yīng)寫(xiě)入“0x64, 0x65, 0x66, 0x67, 0x68”,即“defgh”
     baos.write(ArrayLetters, 3, 5);
    System.out.printf("baos=%s\n", baos);
     // 計(jì)算長(zhǎng)度
     int size = baos.size();
     System.out.printf("size=%s\n", size);
     // 轉(zhuǎn)換成byte[]數(shù)組
     byte[] buf = baos.toByteArray();
     String str = new String(buf);
     System.out.printf("str=%s\n", str);
     // 將baos寫(xiě)入到另一個(gè)輸出流中
     try {
       ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
       baos.writeTo((OutputStream)baos2);
       System.out.printf("baos2=%s\n", baos2);
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }

運(yùn)行結(jié)果:

baos=ABC
baos=ABCdefgh
size=8
str=ABCdefgh
baos2=ABCdefgh

以上就是如何在Java中使用ByteArrayOutputStream,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見(jiàn)到或用到的。希望你能通過(guò)這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

文章標(biāo)題:如何在Java中使用ByteArrayOutputStream
URL鏈接:http://muchs.cn/article32/iepopc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供手機(jī)網(wǎng)站建設(shè)、小程序開(kāi)發(fā)、響應(yīng)式網(wǎng)站、企業(yè)網(wǎng)站制作網(wǎng)站收錄、靜態(tài)網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

綿陽(yáng)服務(wù)器托管