天天看點

java.io.OutputStream.write(byte[] b, int off, int len)方法執行個體

參考位址:https://blog.csdn.net/LWJdear/article/details/72845345

https://www.yiibai.com/java/io/outputstream_write_byte_len.html

java.io.OutputStream.write(byte[] b, int off, int len) 方法從指定的位元組數組開始到目前輸出流關閉寫入len位元組。一般的合約write(b, off, len),一些在數組b中的位元組寫入,以便輸出流;元素b[off]是寫入的第一個位元組和b[off+len-1]是寫的這個操作的最後一個位元組。OutputStream的write方法調用的每個被寫出其中一個位元組參數的write方法。子類被鼓勵重寫此方法,并提供了一個更有效的實作。

如果b為null,一個NullPointerException異常抛出。如果斷為負,或len為負,或者off + len位置大于數組b的長度,則抛出IndexOutOfBoundsException。

聲明

以下是java.io.OutputStream.write()方法的聲明

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

參數

  • b -- 資料
  • off -- 在資料偏移的開始。
  • len -- 寫入的位元組數

傳回值

此方法無傳回值。

異常

  • IOException -- 如果發生I/ O錯誤。特别是IOException,如果是輸出流被關閉抛出。

例子

下面的示例示範java.io.OutputStream.write()方法的用法。

package com.yiibai;

import java.io.*;

public class OutputStreamDemo {

   public static void main(String[] args) {
      byte[] b = {'h', 'e', 'l', 'l', 'o'};
      try {

         // create a new output stream
         OutputStream os = new FileOutputStream("test.txt");

         // craete a new input stream
         InputStream is = new FileInputStream("test.txt");

         // write something
         os.write(b, 0, 3);

         // read what we wrote
         for (int i = 0; i < 3; i++) {
            System.out.print("" + (char) is.read());
         }

      } catch (Exception ex) {
         ex.printStackTrace();
      }


   }
}
      

讓我們編譯和運作上面的程式,這将産生以下結果:

hel      

下面的示例示範java.io.OutputStream.write()方法的用法,循環多次寫入os.write  off偏移指的是 b資料中偏移量。

下面的示例示範java.io.OutputStream.write()方法的用法。

package com.yiibai;


import java.io.*;


public class OutputStreamDemo {


   public static void main(String[] args) {
      byte[] b = {'h', 'e', 'l', 'l', 'o'};
      try {


         // create a new output stream
         OutputStream os = new FileOutputStream("test.txt");


         // craete a new input stream
         InputStream is = new FileInputStream("test.txt");


         // write something
	 for (int i = 0; i < 3 ; i++ ){
	    os.write(b, 1, 4);
	 }


         // read what we wrote
         for (int i = 0; i < 9; i++) {
            System.out.print("" + (char) is.read());
         }


      } catch (Exception ex) {
         ex.printStackTrace();
      }




   }
}      

讓我們編譯和運作上面的程式,這将産生以下結果:

elloelloe