Java.io.BufferedWriter.close()方法範例


java.io.BufferedWriter.close() 重新整理方法從流中的字元,然後將其關閉。關閉後,再write(), append() or flush() 呼叫將丟擲IOException。

宣告

以下是java.io.BufferedWriter.close()方法的宣告

public Writer close()

引數

  • NA

返回值

此方法不返回任何值。

異常

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

例子

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

package com.yiibai;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;

public class BufferedWriterDemo {
   public static void main(String[] args) throws IOException {
      
      StringWriter sw = null;
      BufferedWriter bw = null;
      
      try{
         // create string writer
         sw = new StringWriter();
         
         //create buffered writer
         bw = new BufferedWriter(sw);
         
         // append character.
         bw.append("1");
         
         // close the writer
         bw.close();
         
         // print before appending one more character
         System.out.println(sw.getBuffer());
         
         // appending after closing will throw error
         bw.append("2");
         
         // print after appending one more character
         System.out.println(sw.getBuffer());
            
      }catch(IOException e){
         // if I/O error occurs
         System.out.print("Cannot append, buffered writer is closed");
      }finally{
         // releases any system resources associated with the stream
         if(sw!=null)
            sw.close();
         if(bw!=null)
            bw.close();
      }
   }
}

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

1
Cannot append, buffered writer is closed