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