java.io.Writer.write(String str)方法範例


java.io.Writer.write(String str) 方法寫入一個字串。

宣告

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

public void write(String str)

引數

  • str -- 寫入的字串

返回值

此方法沒有返回值

異常

  • 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
         writer.write(str);

         // flush the writer
         writer.flush();

         // change line and write another string
         writer.write("
This is an example");

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

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

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

Hello world!
This is an example