java.io.Writer.write(String str,int off,int len)方法範例


java.io.Writer.write(String str,int off,int len) 方法將寫入一個字串的一部分。

宣告

以下是java.io.Writer.write()方法的宣告

public void write(String str,int off,int len)

引數

  • str -- 寫入的字串

  • off -- 從開始寫入字元的偏移量

  • len -- 要寫入的字元數

返回值

此方法沒有返回值

異常

  • IndexOutOfBoundsException -- 如果off為負,或len為負,或者off + len位置為負或大於給定字串的長度

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

例子

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

package com.yiibai;

import java.io.*;

public class WriterDemo {

   public static void main(String[] args) {
      String str = "Hello world!";

      // create a new writer
      Writer writer = new PrintWriter(System.out);

      try {
         // write a string portion
         writer.write(str, 0, 5);

         // flush the writer
         writer.flush();

         // write another string portion
         writer.write(str, 5, 6);

         // flush the stream again
         writer.flush();

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

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

Hello world