Java IO 四大附加接口、try-with-resource
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值序列的基本属性,String、CharBuffer、StringBuffer、StringBuilder都实现了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的更多相关文章
- 关于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 ...
- 出错: 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 ...
- 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 ...
- java.io.Serializable 序列化接口
什么是序列化.反序列化? Serialization(序列化)是一种将对象以一连串的字节描述的过程: 反序列化deserialization是一种将这些字节重建成一个对象的过程. 序列化通俗一点说就是 ...
- 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在原来的位置 ...
- Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/config/spring/applicationContext.xml]
在搭建SpringMVC框架的时候遇到了这个问题 问题的原因: 就是没有找到applicatoincontext.xml这个文件, 因为idea自动生成的路径不正确 因此需要再web.xml里面, ( ...
- java IO之AutoCloseable,Closeable和Flushable接口
有3个接口对于流类相当重要.其中两个接口是Closeable和Flushable,它们是在java.io包中定义的,并且是由JDK5添加的.第3个接口是AutoColseable,它是由JDK7添加的 ...
- Java中的Serializable接口transient关键字,及字节、字符、对象IO
1.什么是序列化和反序列化Serialization是一种将对象转为为字节流的过程:deserialization是将字节流恢复为对象的过程. 2.什么情况下需要序列化a)当你想把的内存中的对象保存到 ...
- android java.io.IOException: open failed: EBUSY (Device or resource busy)
今天遇到一个奇怪的问题, 测试在程序的下载界面,下载一个文件第一次下载成功,删除后再下载结果下载报错, 程序:file.createNewFile(); 报错:java.io.IOException: ...
随机推荐
- iOS解析crash日志:
iOS解析crash日志:我们在ios开发中会碰到的很多crash问题,如果Debug调试模式的话,我们可以往往很容易的根据log的输出定位到导致crash的原因,但对于已经上线的应用,或者是rele ...
- tuple 可更改的列表和不可更改的元组
tuple([iterable]) Return a tuple whose items are the same and in the same order as iterable's items. ...
- phonegap 随笔
开发者论坛 http://bbs.phonegapcn.com/forum.php phone调用android本地方法 http://blog.csdn.net/crazyman2010/artic ...
- redis单主机多实例
假设我们服务器上面已经安装好了redis: 可参看:http://zlyang.blog.51cto.com/1196234/1834700 下面我们来配置redis单主机多实例: 我们首先拷贝两份文 ...
- 【IE6的疯狂之十三】IE6下使用滤镜后链接不能点击的BUG
大家可能都知道IE6下使用DXImageTransform.Microsoft.AlphaImageLoader滤镜(用于PNG32 Alpha透明)后链接不能点击的BUG,大家也都知道只要在a标签上 ...
- Mysq 5.7l服务无法启动,没有报告任何错误
昨天系统崩溃了,然后重装了Mysql 5.7 安装步骤和遇到问题及解决方案. 去官网下载Mysql 5.7的解压包(zip),解压到你要安装的目录. 我的安装目录是:D:\Java\Mysql 安装步 ...
- DP! | 不要怂!
跟一个博客刷: http://blog.csdn.net/cc_again/article/details/25866971 一.简单基础dp 1.递推 HDU 2084 #include <b ...
- 面试题-Java基础-异常部分
1.Java中的两种异常类型是什么?他们有什么区别? Java中有两种异常:受检查的(checked)异常和不受检查的(unchecked)异常.不受检查的异常不需要在方法或者是构造函数上声明,就算方 ...
- Qt事件和事件循环
在处理QT循环事件的时候遇到了问题,查了半天资料都没弄明白问题出在哪,后来找大牛同事问了一下,同事就给我写了QCoreApplication::processEvent()这个函数,好啦,终于搞定了, ...
- 七天学会ASP.NET MVC(1-3)源代码下载
原文路径: 中文: http://www.cnblogs.com/powertoolsteam/p/MVC_one.html 英文: http://www.codeproject.com/Artic ...