【自动关闭IO流】

自动关闭IO流,这个是java7提供的,但是有一个前提是必须实现Closeable。try段代码执行完毕后,系统会自动调用资源的关闭方法关闭资源。非常适合有些人频繁操作io可能就会忘记关闭io。

public class InputStreanDemo {
    public static void main(String[] args) {
        File file = new File("H:/test.txt");
        try(//自动关闭IO流(JAVA7)前提是必须实现Closeable
             FileInputStream fileInputStream =new FileInputStream(file);
             FileOutputStream fileOutputStream = new FileOutputStream("H:/test1.txt")
        ) {
            int len = 0;
            //read方法,若字符为文件末尾则返回值为-1
            while ((len = fileInputStream.read()) != -1) {
                fileOutputStream.write(len);
            }
        }catch (Exception e){
        }
    }
}

点进去FileInputStream 或者FileOutputStream 可以看见
【自动关闭IO流】_第1张图片
FileInputStream 继承了InputStream, FileOutputStream 继承了OutputStream,继续点进去看。
【自动关闭IO流】_第2张图片
里面实现了Closeable。而Closeable继承自AutoCloseable,这两个接口中只有一个方法:void close() throws Exception;
【自动关闭IO流】_第3张图片

你可能感兴趣的:(java,大数据,开发语言)