java.io.BufferedInputStream.write(byte[] b, int off, int len)方法範例


java.io.BufferedInputStream.write(byte[] b, int off, int len) 方法從指定的位元組陣列b的起始位置,到底層輸出流寫入len個位元組。

宣告

以下是 java.io.DataOutputStream.write(byte[] b, int off, int len)方法的宣告:

public void write(byte[] b, int off, int len)

引數

  • b -- 源緩衝區。

  • off -- 起始位置。

  • len -- 寫入到流的位元組數。

返回值

此方法不返回任何值。

異常

  • IOException -- 如果發生I/ O錯誤。

例子

下面的例子顯示java.io.DataOutputStream.write(byte[] b, int off, int len)方法的用法。

package com.yiibai;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class DataOutputStreamDemo {
   public static void main(String[] args) throws IOException {
         
      ByteArrayOutputStream baos = null;
      DataOutputStream dos = null;
      byte[] buf = {87,64,72,31,90};
      
      try{
         // create byte array output stream
         baos = new ByteArrayOutputStream();
         
         // create data output stream
         dos = new DataOutputStream(baos);
         
         // write to the stream from the source buffer
         dos.write(buf, 2, 3);
         
         // flushes bytes to underlying output stream
         dos.flush();
   
         // for each byte in the baos buffer content
         for(byte b:baos.toByteArray())
         {
            System.out.println(b);
         }
      }catch(Exception e){
         // if any error occurs
         e.printStackTrace();
      }finally{
         
         // releases all system resources from the streams
         if(dos!=null)
            dos.close();
         if(baos!=null)
            baos.close();
      }
   }
}

讓我們編譯和執行上面的程式,這將產生以下結果:

72
31
90