WebView(网络视图)的两种使用方式
try
-with-resources语句是一个声明一个或多个资源的 try
语句。一个资源作为一个对象,必须在程序结束之后随之关闭。 try
-with-resources语句确保在语句的最后每个资源都被关闭 。任何实现了 Java.lang.AutoCloseable的对象
, 包括所有实现了 java.io.Closeable的对象
, 都可以用作一个资源。
- /**
- * A {@code Closeable} is a source or destination of data that can be closed.
- * The close method is invoked to release resources that the object is
- * holding (such as open files).
- *
- * @since 1.5
- */
- public interface Closeable extends AutoCloseable {
其实Closeable继承AutoCloseable 的。
示例1:下面的例子读取文件的第一行。它使用了 BufferedReader
的一个实例来读取文件中的数据。BufferedReader
是一个资源,它必须在程序结束之后随之关闭:
- public static String readFirstLineFromFile(String path) throws IOException {
- try (BufferedReader br = new BufferedReader(new FileReader(path))) {
- return br.readLine();
- }
- }
在这个例子中, try
-with-resources 语句声明的资源是一个 BufferedReader
。声明语句在紧跟在 try
关键字的括号里面。Java SE 7以及后续版本中,BufferedReader类实现了
java.lang.AutoCloseable接口
。 因为 BufferedReader
实例是在 try
-with-resource 语句中声明的, 所以不管 try
语句正常地完成或是发生意外 (结果就是 BufferedReader.readLine 方法抛出IOException),BufferedReader都将会关闭。
测试一把,如果try后面的括号里面有实例不是继承AutoCloseable接口是怎样的
同时看看BufferReader:
- public abstract class Reader implements Readable, Closeable
对比版本:在 Java SE 7之前, 可以使用 finally
块来确保资源被关闭,不管 try
语句正常地完成或是发生意外。下面的例子使用 finally
块替换 try
-with-resources 语句:
- public static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
- BufferedReader br = new BufferedReader(new FileReader(path));
- try {
- return br.readLine();
- } finally {
- if (br != null)
- br.close();
- }
- }
然而,在这个例子中,如果 readLine
和 close
方法均抛出异常,那么 readFirstLineFromFileWithFinallyBlock
方法将抛出从 finally
块中抛出的异常; try
块中抛出的异常被抑制了。与此相反, 在 readFirstLineFromFile这个例子中
, 如果 try
块和 try
-with-resources 语句均抛出异常, 那么 readFirstLineFromFile
将抛出从 try
块中抛出的异常; try
-with-resources 块抛出的异常被抑制了。在Java SE 7 以及后续的版本中, 你可以检索被抑制的异常;详情参见 Suppressed Exceptions。
示例2:资源的 close
方法调用顺序与它们的创建顺序相反。
可以在一个 try
-with-resources 语句中声明一个或多个资源。下面的例子检索zip文件 zipFileName
中所有文件的名称并创建一个包含那些文件名称的文本文件:
- public static void writeToFileZipFileContents(String zipFileName, String outputFileName)
- throws java.io.IOException {
- java.nio.charset.Charset charset = java.nio.charset.Charset.forName("US-ASCII");
- java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName);
- // Open zip file and create output file with try-with-resources
- // statement
- try (java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
- java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)) {
- // Enumerate each entry
- for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) {
- // Get the entry name and write it to the output file
- String newLine = System.getProperty("line.separator");
- String zipEntryName = ((java.util.zip.ZipEntry) entries.nextElement()).getName() + newLine;
- writer.write(zipEntryName, 0, zipEntryName.length());
- }
- }
- }
在这个例子中, try
-with-resources 语句包含两个由分号隔开的声明: ZipFile
和 BufferedWriter
。当代码块直接伴随着它正常地或由于一个异常终止时, BufferedWriter
和 ZipFile对象的
close
方法以这种顺序自动地调用 。注意:资源的 close
方法调用顺序与它们的创建顺序相反。
- public class ZipFile implements ZipConstants, Closeable {
- public abstract class Writer implements Appendable, Closeable, Flushable {
- /**
- * A {@code Closeable} is a source or destination of data that can be closed.
- * The close method is invoked to release resources that the object is
- * holding (such as open files).
- *
- * @since 1.5
- */
- public interface Closeable extends AutoCloseable {
示例3:
下面的例子使用一个 try
-with-resources 语句来自动关闭一个 java.sql.Statement
对象:
- public static void viewTable(Connection con) {
- String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";
- try (Statement stmt = con.createStatement()) {
- ResultSet rs = stmt.executeQuery(query);
- while (rs.next()) {
- String coffeeName = rs.getString("COF_NAME");
- int supplierID = rs.getInt("SUP_ID");
- float price = rs.getFloat("PRICE");
- int sales = rs.getInt("SALES");
- int total = rs.getInt("TOTAL");
- System.out.println(coffeeName + ", " + supplierID + ", " + price + ", " + sales + ", " + total);
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
这个例子中使用的 java.sql.Statement
这个资源是JDBC 4.1以及后续版本API的一部分。
注意: 一个 try
-with-resources 语句可以像普通的 try
语句那样有 catch
和 finally
块。在try
-with-resources 语句中, 任意的 catch
或者 finally
块都是在声明的资源被关闭以后才运行。
被抑制的异常
与 try
-with-resources 语句关联的代码块可能会抛出异常。在 writeToFileZipFileContents这个例子中
, 当试图关闭 ZipFile
和 BufferedWriter
对象时,try
块可能会抛出一个异常,并且 try
-with-resources 语句可能抛出多达两个异常 。如果 try
块抛出异常并且 try
-with-resources 语句抛出一个或多个异常,那么从 try
-with-resources 语句中抛出的异常将会被抑制, 并且块抛出的异常是由 writeToFileZipFileContents
方法抛出的那一个。你可以通过调用由 try块抛出的异常的
Throwable.getSuppressed
方法检索这些被抑制的异常信息。
实现了AutoCloseable 或 Closeable 接口的类
参见 AutoCloseable
和 Closeable
接口的Javadoc可以看到实现了两者当中的任何一个接口的类集。Closeable
接口继承了 AutoCloseable
接口。 Closeable
接口的 close
方法抛出IOException
类型的异常而 AutoCloseable
接口的 close
方法抛出 Exception 类型的异常。
因此, subclasses of the AutoCloseable
接口的子类可以重写 close
方法的这个行为来抛出指定的异常,例如 IOException
, 或者没有异常。
使用try-with-resource方法之后有如下两个好处:
- 代码变得简洁可读
- 所有的资源都托管给try-with-resource语句,能够保证所有的资源被正确关闭,再也不用担心资源关闭的问题。
WebView(网络视图)的两种使用方式的更多相关文章
- kotlin for android----------MVP模式下(OKHttp和 Retrofit+RxJava)网络请求的两种实现方式
今天要说的干货是:以Kotlin,在MVP模式下(OKHttp和 Retrofit+RxJava)网络请求两种实现方式的一个小案例,希望对大家有所帮助,效果图: Retrofit是Square公司开发 ...
- iOS- 网络请求的两种常用方式【GET & POST】的区别
GET和POST 网络请求的两种常用方式的实现[GET & POST] –GET的语义是获取指定URL上的资源 –将数据按照variable=value的形式,添加到action所指向的URL ...
- Android中BroadcastReceiver的两种注册方式(静态和动态)详解
今天我们一起来探讨下安卓中BroadcastReceiver组件以及详细分析下它的两种注册方式. BroadcastReceiver也就是"广播接收者"的意思,顾名思义,它就是用来 ...
- WDS 的两种实现方式
转自:http://blog.chinaunix.net/uid-26527046-id-3627627.html WDS 的两种实现方式 WDS(Wireless Distribution Syst ...
- Adobe Acrobat XI Pro 两种破解方式 Keygen秘钥 license替换 亲测有效
大家平时看paper比较多的话想必都是用Adobe Acrobat而非Adobe Reader吧,其功能全面之处就不啰嗦了,下面给大家分享下Adobe Acrobat XI Pro的两种破解方式(两种 ...
- Android进程通信之一:两种序列化方式
2月下旬辞职了,去海南度假到现在,领略了一把三亚风情也算任性和 然而这样任性带来的后果就是..不行了我必须吐槽一句.. 没毕业的找工作就这么难嘛!投了57家一家面试机会都没有,好歹给个面试机会啊!!本 ...
- Nginx 和 PHP 的两种部署方式比较
2种部署方式简介 第一种 前置1台nginx服务器做HTTP反向代理和负载均衡 后面多态服务器部署Nginx Web服务和php-fpm提供的fast cgi服务 第二种 前置1台nginx服务器做W ...
- iOS- 网络访问两种常用方式【GET & POST】实现的几个主要步骤
1.前言 上次,在博客里谈谈了[GET & POST]的区别,这次准备主要是分享一下自己对[GET & POST]的理解和实现的主要步骤. 在这就不多废话了,直接进主题,有什么不足的欢 ...
- Android四大组件之服务的两种启动方式详解
Service简单概述 Service(服务):是一个没有用户界面.可以在后台长期运行且可以执行操作的应用组件.服务可由其他应用组件启动(如:Activity.另一个service).此外,组件可以绑 ...
随机推荐
- C++ Variables and Basic Types Notes
1. Type conversion: If we assign an out-of-range value to an object of unsigned type, the result is ...
- 【转】Wireshark:“There are no interfaces on which a capture can be done ”
linux环境下 两种解决方案: 第一种方法:使用root用户登陆 xiaoshancun@xiaoshancun-VM500:~$ sudo wireshark 第二种方法 ...
- Spring 注入static变量
一般我们我想注入一个static的变量,如下: @Autowired private static String str; 不过,这样最终结果为null. 1.使用配置文件的方式注入 priva ...
- 可持久化trie 学习总结
QAQ 以前一直觉得可持久化trie很难,今天强行写了一发觉得还是蛮简单的嘛 自己的模板是自己手写的,写了几道题目并没有出过错误 THUSC的第二题的解法五貌似就是可持久化trie,时间复杂度O(60 ...
- lintcode 中等题:permutations 全排列
题目 全排列 给定一个数字列表,返回其所有可能的排列. 您在真实的面试中是否遇到过这个题? Yes 样例 给出一个列表[1,2,3],其全排列为: [ [1,2,3], [1,3,2], [2,1,3 ...
- 【Linux高频命令专题(9)】ls
ls命令是linux下最常用的命令.ls命令就是list的缩写缺省下ls用来打印出当前目录的清单如果ls指定其他目录那么就会显示指定目录里的文件及文件夹清单. 通过ls 命令不仅可以查看linu ...
- Debug过程中的mock (及display窗口的使用)
转载:http://m.blog.csdn.net/blog/u012516903/18004965 在debug的时候,有3个地方可以进行mock测试 测试代码如下: 1.使用display窗口 W ...
- linux内核--进程与线程
http://blog.csdn.net/yusiguyuan/article/details/12154823 在<linux内核设计与实现>中第三章讲解了进程管理,在关于进程和线程的概 ...
- Java学习笔记之:Java的数据类型
一.介绍 变量就是申请内存来存储值.也就是说,当创建变量的时候,需要在内存中申请空间. 内存管理系统根据变量的类型为变量分配存储空间,分配的空间只能用来储存该类型数据. Java语言提供了八种基本类型 ...
- 解决Nginx下WordPress后台404的问题
在把这个博客做好后,上传到nginx服务器上却出现问题. 首先是wordpress官方的伪静态是通过.htaccess实现的,但nginx并不支持.htaccess,无奈只好在网上找到wordpres ...