Java.io.Writer.write() 方法



描述

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.tutorialspoint;

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
java_io_writer.htm
廣告
© . All rights reserved.