當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Java.io.BufferedWriter.close()用法及代碼示例


描述

這個java.io.BufferedWriter.close()方法從流中刷新字符,然後關閉它。關閉後,進一步的 write()、append() 或 flush() 調用將拋出 IOException。

聲明

以下是聲明java.io.BufferedWriter.close()方法

public Writer close()

參數

NA

返回值

此方法不返回任何值。

異常

IOExceptionâˆ' 如果發生 I/O 錯誤..

示例

下麵的例子展示了使用public Writer close()方法。

package com.tutorialspoint;

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

相關用法


注:本文由純淨天空篩選整理自 Java.io.BufferedWriter.close() Method Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。