Java IO 四大附加接口、try-with-resource

@author ixenos

四大附加接口 Closeable、Flushable、Readable、Appendable


Closeable:

  void close() throws IOException 关闭此流并释放与此流关联的所有系统资源

  java.io.closeable扩展了java.lang.AutoCloseable,因此,对任何Closeable进行操作时,都可以使用try-with-resources语句

  • try-with-resources 可以声明一个或多个资源,资源之间用分号隔开。
  •  try (
    java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
    java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
    ) {
    ...
    }

  有关 try-with-resource 特性的具体分析请见下文。

Flushable:

  void flush() 将所有已缓冲输出写入底层流

Readable:

  int read(CharBuffer cb) 形参中的CharBuffer类拥有按顺序随机地进行读写访问的方法,它表示一个内存中的缓冲区或者一个内存映像(虚拟内存)的文件

  

Appendable:

  Appendable append(char c) 添加的单个字符

  Appendable append(CharSequence s) 添加字符序列,CharSequence接口描述了一个char值序列的基本属性,StringCharBufferStringBufferStringBuilder都实现了CharSequence,所以可以传入这些类型的对象

  以上两个方法,都返回this

四大IO抽象类与附加接口的关系


1、InputStream、OutputStream、Reader、Writer都实现了Closeable和AutoCloseable接口,因此,都可以使用 try-with-resources 语句

2、OutputStream、Writer实现了Flushable接口

3、Reader实现了Readable接口

4、Writer实现了Appendable接口

try-with-resource


try-with-resource 是Java SE 7 加入AutoCloseable接口后才有的,closeable接口继承了AutoCloseable接口。

  AutoCloseable接口规定了自动关闭资源:

The close() method of an AutoCloseable object is called automatically when exiting a try-with-resources block for which the object has been declared in the resource specification header.

1、这个所谓的try-with-resources,是个语法糖。实际上就是自动调用资源的close()函数。

 public class TryStudy implements AutoCloseable{
static void test() throws Exception {
try(TryStudy tryStudy = new TryStudy()){
System.out.println(tryStudy);
}
}
@Override
public void close() throws Exception {
}
}

2、可以在一个 try-with-resources 语句中声明一个或多个资源(用分号隔开),但要注意资源的 close 方法调用顺序与它们的创建顺序相反

 try (
java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
)

  资源的close方法在JVM中的调用顺序是: writer.close()   zf.close()

3、下面从编绎器生成的字节码来分析下,try-with-resources到底是怎样工作的:

  TryStudy实现了AutoCloseable接口,下面来看下test函数的字节码:

 static test()V throws java/lang/Exception
TRYCATCHBLOCK L0 L1 L2
TRYCATCHBLOCK L3 L4 L4
L5
LINENUMBER 21 L5
ACONST_NULL
ASTORE 0
ACONST_NULL
ASTORE 1
L3
NEW TryStudy
DUP
INVOKESPECIAL TryStudy.<init> ()V
ASTORE 2
L0
LINENUMBER 22 L0
GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
ALOAD 2
INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/Object;)V
L1
LINENUMBER 23 L1
ALOAD 2
IFNULL L6
ALOAD 2
INVOKEVIRTUAL TryStudy.close ()V
GOTO L6
L2
FRAME FULL [java/lang/Throwable java/lang/Throwable TryStudy] [java/lang/Throwable]
ASTORE 0
ALOAD 2
IFNULL L7
ALOAD 2
INVOKEVIRTUAL TryStudy.close ()V
L7
FRAME CHOP 1
ALOAD 0
ATHROW
L4
FRAME SAME1 java/lang/Throwable
ASTORE 1
ALOAD 0
IFNONNULL L8
ALOAD 1
ASTORE 0
GOTO L9
L8
FRAME SAME
ALOAD 0
ALOAD 1
IF_ACMPEQ L9
ALOAD 0
ALOAD 1
INVOKEVIRTUAL java/lang/Throwable.addSuppressed (Ljava/lang/Throwable;)V
L9
FRAME SAME
ALOAD 0
ATHROW
L6
LINENUMBER 24 L6
FRAME CHOP 2
RETURN
LOCALVARIABLE tryStudy LTryStudy; L0 L7 2
MAXSTACK = 2
MAXLOCALS = 3

从字节码里可以看出,的确是有判断tryStudy对象是否为null,如果不是null,则调用close函数进行资源回收。

try-with-resource与异常捕获


1、从 被丢弃 到 被抑制 的异常 Suppressed Exceptions

  再仔细分析,可以发现有一个Throwable.addSuppressed的调用,那么这个调用是什么呢?

  使用了try-catch语句之后(try-with-resource也算是try-catch),有可能会出现两种异常,一个是try块里的异常,一个是调用close函数里抛出的异常。

  a) 在JDK1.7 以前,一旦finally块抛出了close函数里的异常,前面try块catch的异常被丢弃了!

  b) 而在 try-with-resources 语句中如果在调用close函数时出现异常(注意这个前提),那么前面的异常就被称为Suppressed Exceptions,因此Throwable还有个addSuppressed函数可以把它们保存起来,当用户捕捉到close里抛出的异常时,就可以调用Throwable.getSuppressed函数来取出close之前的异常了。

2、注意:

   一个 try-with-resources 语句可以像普通的 try 语句那样有 catch 和 finally 块。

  但是在try-with-resources 语句中, 任意的 catch 或者 finally 块都是在声明的资源被关闭以后才运行。

3、catch多种异常,但抛出一种异常时

  在JDK1.7之前catch多个异常是这样的:

         try{
//逻辑代码
}catch (IOException ex) {
logger.log(ex);
throw new SpecialException();
catch (SQLException ex) {
logger.log(ex);
throw new SpecialException();
}

从上述代码中可以看出这样写非常的难看,并且会出现许多重复的代码。

JDK1.7及以后可以这样:

         try{
//逻辑代码
}catch (IOException | SQLException ex) {
logger.log(ex);
throw new SpecialException();
}

注:上面例子中的ex是隐式的final不可以在catch块中改变ex。

4、在JDK1.7以前的版本,在方法声明中声明抛出的异常如果在方法体内没有抛出时不被允许的,如下:

 static class FirstException extends Exception { 

 }

 static class SecondException extends Exception {

 }

 public void rethrowException(String exceptionName) throws Exception {

   try {

     if (exceptionName.equals("First")) {
//如果异常名称为"First",则抛出异常一
throw new FirstException(); } else {
//否则的话,则抛出异常二
throw new SecondException(); } } catch (Exception e) { throw e;
}
}

JDK1.7及以后版本:

 static class FirstException extends Exception { 

 }

 static class SecondException extends Exception {

 }

 public void rethrowException(String exceptionName) throws Exception, FirstException, SecondException {
try {
// 逻辑代码
}catch (Exception e) { throw e;
}
}

Java IO 四大附加接口、try-with-resource的更多相关文章

  1. 关于SpringMVC项目报错:java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/xxxx.xml]

    关于SpringMVC项目报错:java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/xxxx ...

  2. 出错: IOException parsing XML document from ServletContext resource [/cn.mgy.conig]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/cn.mgy.conig]

    错误的详细内容: 严重: StandardWrapper.Throwable org.springframework.beans.factory.BeanDefinitionStoreExceptio ...

  3. IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/app

    web.xml初始化spring容器出错 org.springframework.beans.factory.BeanDefinitionStoreException: IOException par ...

  4. java.io.Serializable 序列化接口

    什么是序列化.反序列化? Serialization(序列化)是一种将对象以一连串的字节描述的过程: 反序列化deserialization是一种将这些字节重建成一个对象的过程. 序列化通俗一点说就是 ...

  5. Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/dispatcher-servlet.xml]

    这是因为我把 [/WEB-INF/dispatcher-servlet.xml]的位置换成了[config/springmvc/dispatcher-servlet.xml] 因此idea在原来的位置 ...

  6. Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/config/spring/applicationContext.xml]

    在搭建SpringMVC框架的时候遇到了这个问题 问题的原因: 就是没有找到applicatoincontext.xml这个文件, 因为idea自动生成的路径不正确 因此需要再web.xml里面, ( ...

  7. java IO之AutoCloseable,Closeable和Flushable接口

    有3个接口对于流类相当重要.其中两个接口是Closeable和Flushable,它们是在java.io包中定义的,并且是由JDK5添加的.第3个接口是AutoColseable,它是由JDK7添加的 ...

  8. Java中的Serializable接口transient关键字,及字节、字符、对象IO

    1.什么是序列化和反序列化Serialization是一种将对象转为为字节流的过程:deserialization是将字节流恢复为对象的过程. 2.什么情况下需要序列化a)当你想把的内存中的对象保存到 ...

  9. android java.io.IOException: open failed: EBUSY (Device or resource busy)

    今天遇到一个奇怪的问题, 测试在程序的下载界面,下载一个文件第一次下载成功,删除后再下载结果下载报错, 程序:file.createNewFile(); 报错:java.io.IOException: ...

随机推荐

  1. windows 下安装Python

    一.下载 官网地址:https://www.python.org/,64位的版本 二.安装 32位和64位的版本安装起来没有区别,双击打开后,第一步要记得勾上add python to Path 选项 ...

  2. Spring 注解式Aop 入门

    首先在spring配置文件中加上 xmlns:aop="http://www.springframework.org/schema/aop" http://www.springfr ...

  3. MVC JsonResult

    public JsonResult GetJson() { var res = new JsonResult(); res.Data = new {isSucceed = true, returnMs ...

  4. MyEclipse 中文注释乱码

    window-->preference-->general-->content type然后在<Content Types>中展开每一个子项,并在<Default ...

  5. 获取usb设备父系或子代

    /// <summary> /// 获取设备父系 /// </summary> /// <param name="driver"></pa ...

  6. android 开发心得杂记

    1.Android周刊关注. 2.4季Android性能优化典范 胡凯 http://mp.weixin.qq.com/s?__biz=MzA4NTQwNDcyMA==&mid=4021354 ...

  7. Oracle的闪回技术--闪回错误的DML操作

    提交DML操作后,该操作使用的还原段就可以被其它对象使用了,为了保证闪回操作时这些数据仍然被保存在还原段中,可能需要重新设置undo_retention参数,表示一个事务提交后,该事务的数据必须保存在 ...

  8. <hdu-2032>杨辉三角

    这是杭电hdu上杨辉三角的链接:http://acm.hdu.edu.cn/showproblem.php?pid=2032  Problem Description: 还记得中学时候学过的杨辉三角吗 ...

  9. scala 访问权限详解

    private/protected [包名/类名/this] 即可指定变量的作用域.(this代表只有当前实例(即对象)可以访问) 伴生类和伴生对象中的成员可以相互访问. class PackageO ...

  10. BAPI_GOODSMVT_CREATE 移动类型311 CODE = '04' 代码

    DATA: MAT_DOC LIKE BAPI2017_GM_HEAD_RET-MAT_DOC.      "物料凭证编号   DATA: GMHEAD LIKE BAPI2017_GM_H ...