自动关闭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 可以看见

FileInputStream 继承了InputStream, FileOutputStream 继承了OutputStream,继续点进去看。

里面实现了Closeable。而Closeable继承自AutoCloseable,这两个接口中只有一个方法:void close() throws Exception;

Java 7自动关闭IO流实践:Closeable接口的应用
本文介绍Java 7中如何通过try-with-resources语句自动关闭FileInputStream和FileOutputStream,强调了Closeable接口的重要性,以及其在防止资源泄露方面的便捷性。
1330

被折叠的 条评论
为什么被折叠?



