Java BufferedWriter close()方法

java.io.BufferedWriter.close() 用于关闭输入流。关闭后,调用write(),append()或flush()方法将引发IOException异常。

1 语法

public Writer close()

2 参数

3 返回值

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.BufferedWriter.close()方法的例子
 */
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;

public class Demo {
    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

热门文章

优秀文章