Java InputStreamReader close()方法

java.io.InputStreamReader.close() 方法关闭输入流读取和调用read(), ready(), mark(), reset()和 skip() 在一个封闭的流的方法会抛出IOException异常。

1 语法

public void close()

2 参数

3 返回值

4 示例 

package com.yiidian;

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

public class Demo {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = null;
        InputStreamReader isr = null;
        int i;
        char c;

        try {
            // new input stream reader is created
            fis = new FileInputStream("d:/test.txt");
            isr = new InputStreamReader(fis);

            // input stream reader is closed
            isr.close();
            System.out.print("close() invoked");

            // read() called after closed method
            i = isr.read();
            c = (char)i;
            System.out.println(c);

        } catch (Exception e) {
            // print error
            System.out.print("The stream is already closed");
        } finally {
            // closes the stream and releases resources associated
            if(fis!=null)
                fis.close();
            if(isr!=null)
                isr.close();
        }
    }
}

假设test.txt内容为:

ABCDE

输出结果为:

close() invokedThe stream is already closed

热门文章

优秀文章