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. JS判断在哪个浏览器打开

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http ...

  2. 基于Unity的Profiler性能分析

    A. WaitForTargetFPS:       Vsync(垂直同步)功能所,即显示当前帧的CPU等待时间    B. Overhead:       Profiler总体时间-所有单项的记录时 ...

  3. JavaSE中主要的类与方法

    1.instanceof:测试左边的对象是否是右边类的实例;  数组.length:返回的是数组的长度; 2.Scanner类     nextInt():读取键盘录入的整数;  next():读取键 ...

  4. 免费SSL证书申请

    https://buy.wosign.com/free/#apply 和 http://www.startssl.com/

  5. Submission

    EI: ICIC Express Letters: http://www.icicelb.org/elb/index.html IJICIC: http://www.ijicic.net/ijicic ...

  6. 我是如何给discuz模板做语法高亮的

    本人一直做ASP.NET开发,近期接到任务要用Discuz开发一个社区,第一次接触PHP,PHP灵活的语法,天生的模块化,各种语法糖深深的震惊了我,我从内心深处感受到了PHP是最牛逼的语言!!! 好了 ...

  7. StringBuffer使用append提示String concatenation as argument to 'StringBuffer.append()' call

    昨天发现一个IDE提示: String concatenation as argument to 'StringBuffer.append()' call less... (Ctrl+F1) Repo ...

  8. 用Redis作为Mysql数据库的缓存【转】

    用Redis作Mysql数据库缓存,必须解决2个问题.首先,应该确定用何种数据结构存储来自Mysql的数据:在确定数据结构之后,还要考虑用什么标识作为该数据结构的键. 直观上看,Mysql中的数据都是 ...

  9. swift 经典代码收集 和 赏析

    代码1:protocol PickableEnum { var displayName: String { get } var permanentID: String { get } static v ...

  10. iosAPP打包上架xcode中Archive提交成功以后,不提示构建版本问题

    最近在项目更新时遇到Archive提交到开发者中心成功后,一直不提示构建版本信息,可能导致的原因是由于ios10以后对于APP中调用手机相册或摄像头麦克风时需要配置plist文件,配置如下内容或许会解 ...