/**
* 当结束一个流的时候,要关闭这个流,这会释放与这个流有关的所有资源,如文件句柄或者端口。如果这个流来自网络连接,那么关闭会终止这个链接
* ,一旦输出流关闭,在继续写入就会抛出IOException异常。不过有些流仍允许对这个对象做一些处理,例如,关闭的ByteArrayOutputStream仍然可以转换为
* 实际的字节数组,关闭的DigestOutputStream仍然可以返回其摘要。
* 如果一个长时间运行的程序,没有关闭流,则可能会泄露句柄网络端口和其他资源。明智的做法是在一个finally块中关闭流。
* finally块可以确保里面的代码始终执行,无论前面的代码是否抛出异常。
* @param args
*/
public static void main(String[] args) {
OutputStream out=null;
try {
out=new FileOutputStream("E://acci.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* java7中引入带资源的try构造,可以简单的完成这个清理,不需要在try块之外声明流变量,完全可以在try块的一个参数中声明,
* 现在不需要finally子句,java会对try块参数中声明的所有AutoCloseable对象自动调用close()方法。
* 只要对象实现了closeable接口,都可以使用“带资源的try块”这包括几乎所有需要释放资源的对象。
* 列外:Java MailTransport对象。这些对象还需要显示的释放。
*/
public void testOutputStreamTry(){
try(OutputStream out=new FileOutputStream("E://acci.txt")){
}catch (IOException e) {
System.err.println(e.getMessage());
}
}