试用期java

Today we will look into Java Try with Resources. One of the Java 7 feature is try-with-resources statement for automatic resource management.

今天,我们将研究Java试用资源。 Java 7的功能之一是用于自动资源管理的try-with-resources语句。

尝试使用资源 (Try with Resources)

A resource is an object that must be closed once your program is done using it. For example, a File resource or JDBC resource for a database connection or a Socket connection resource. Before Java 7, there was no auto resource management and we should explicitly close the resource once our work is done with it. Usually, it was done in the finally block of a try-catch statement. This approach used to cause memory leaks and performance hit when we forgot to close the resource.

资源是一个对象,一旦您的程序完成使用它就必须关闭它。 例如,用于数据库连接或套接字连接资源的文件资源或JDBC资源。 在Java 7之前,没有自动资源管理,一旦完成工作,就应该显式关闭资源。 通常,它是在try-catch语句的finally块中完成的。 当我们忘记关闭资源时,这种方法曾经导致内存泄漏和性能下降。

Let’s see a pseudo code snippet to understand this java try with resources feature.

让我们看一个伪代码片段,以理解此Java资源尝试功能。

Before Java 7:

在Java 7之前

try{//open resources like File, Database connection, Sockets etc
} catch (FileNotFoundException e) {// Exception handling like FileNotFoundException, IOException etc
}finally{// close resources
}

Java 7 try with resources implementation:

Java 7尝试使用资源实现

try(// open resources here){// use resources
} catch (FileNotFoundException e) {// exception handling
}
// resources are closed as soon as try-catch block is executed.

Let’s write a simple program to read a file and print the first line using Java 6 or older versions and Java 7 try-with-resources implementation.

让我们编写一个简单的程序来读取文件并使用Java 6或更早版本和Java 7 try-with-resources实现打印第一行。

Java 6资源管理示例 (Java 6 Resource Management Example)

package com.journaldev.util;import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;public class Java6ResourceManagement {public static void main(String[] args) {BufferedReader br = null;try {br = new BufferedReader(new FileReader("C:\\journaldev.txt"));System.out.println(br.readLine());} catch (IOException e) {e.printStackTrace();} finally {try {if (br != null)br.close();} catch (IOException ex) {ex.printStackTrace();}}}
}

Java 7试用资源示例 (Java 7 Try With Resources Example)

package com.journaldev.util;import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;public class Java7ResourceManagement {public static void main(String[] args) {try (BufferedReader br = new BufferedReader(new FileReader("C:\\journaldev.txt"))) {System.out.println(br.readLine());} catch (IOException e) {e.printStackTrace();}}
}

Java试用资源的好处 (Java try with resources benefits)

Some of the benefits of using try with resources in java are;

在Java中对资源使用try的一些好处是;

  1. More readable code and easy to write.更具可读性的代码,易于编写。
  2. Automatic resource management.自动资源管理。
  3. Number of lines of code is reduced.代码行数减少。
  4. No need of finally block just to close the resources.无需最终阻塞即可关闭资源。
  5. We can open multiple resources in try-with-resources statement separated by a semicolon. For example, we can write following code:
    try (BufferedReader br = new BufferedReader(new FileReader("C:\\journaldev.txt"));java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(FileSystems.getDefault().getPath("C:\\journaldev.txt"), Charset.defaultCharset())) {System.out.println(br.readLine());} catch (IOException e) {e.printStackTrace();}

    我们可以在以分号分隔的try-with-resources语句中打开多个资源。 例如,我们可以编写以下代码:

  6. When multiple resources are opened in try-with-resources, it closes them in the reverse order to avoid any dependency issue. You can extend my resource program to prove that.当在try-with-resources中打开多个资源时,它将以相反的顺序关闭它们,以避免任何依赖关系问题。 您可以扩展我的资源计划以证明这一点。

Java 7 has introduced a new interface java.lang.AutoCloseable. To use any resource in try-with-resources, it must implement AutoCloseable interface else java compiler will throw compilation error.

Java 7引入了新接口java.lang.AutoCloseable 。 要在try-with-resources中使用任何资源,它必须实现AutoCloseable接口,否则Java编译器将抛出编译错误。

Lets confirm this with an example:

让我们用一个例子来确认这一点:

package com.journaldev.util;import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;public class Java7ResourceManagement {public static void main(String[] args) {try (MyResource mr = new MyResource()) {System.out.println("MyResource created in try-with-resources");} catch (Exception e) {e.printStackTrace();}System.out.println("Out of try-catch block.");}static class MyResource implements AutoCloseable{@Overridepublic void close() throws Exception {System.out.println("Closing MyResource");}}
}

The output of the above program is:

上面程序的输出是:

MyResource created in try-with-resources
Closing MyResource
Out of try-catch block.

From the output, it’s clear that as soon as the try-catch block is finished, the resource close method is called.

从输出中很明显,一旦try-catch块完成,就将调用资源关闭方法。

尝试使用资源异常 (Try with Resources Exceptions)

There is one difference to note between try-catch-finally and try-with-resources in case of exceptions.

在出现异常的情况下,try-catch-finally和try-with-resources之间有一个区别。

If an exception is thrown in both try block and finally block, the method returns the exception thrown in finally block.

如果在try块和finally块中都抛出了异常,则该方法返回在finally块中抛出的异常。

For try-with-resources, if an exception is thrown in a try block and in a try-with-resources statement, then the method returns the exception thrown in the try block.

对于try-with-resources,如果在try块和try-with-resources语句中引发了异常,则该方法将返回在try块中引发的异常。

To better clarify this difference, we will see sample code.

为了更好地阐明这种差异,我们将看到示例代码。

package com.journaldev.util;public class Java7ResourceManagement {public static void main(String[] args) throws Exception {try {tryWithResourceException();} catch (Exception e) {System.out.println(e.getMessage());}try {normalTryException();} catch (Exception e) {System.out.println(e.getMessage());}}private static void normalTryException() throws Exception {MyResource mr = null;try {mr = new MyResource();System.out.println("MyResource created in the try block");if (true)throw new Exception("Exception in try");} finally {if (mr != null)mr.close();}}private static void tryWithResourceException() throws Exception {try (MyResource mr = new MyResource()) {System.out.println("MyResource created in try-with-resources");if (true)throw new Exception("Exception in try");}}static class MyResource implements AutoCloseable {@Overridepublic void close() throws Exception {System.out.println("Closing MyResource");throw new Exception("Exception in Closing");}}
}

The output of the above program is:

上面程序的输出是:

MyResource created in try-with-resources
Closing MyResource
Exception in try
MyResource created in the try block
Closing MyResource
Exception in Closing

The output of the program proves the difference given above. That’s all for the Java 7 try-with-resources.

程序的输出证明了上面给出的差异。 这就是Java 7 try-with-resources的全部内容。

翻译自: https://www.journaldev.com/592/java-try-with-resources

试用期java

试用期java_Java试用资源相关推荐

  1. 试用期java_Java 7试用资源

    试用期java Java 7为完成使用后需要关闭的资源(例如文件,流,数据库连接和套接字)提供了更好的资源管理. 这种语言构造称为try-with-resources语句. 完成这项工作的机制称为Au ...

  2. Java 7试用资源

    Java 7为完成使用后需要关闭的资源(例如文件,流,数据库连接和套接字)提供了更好的资源管理. 这种语言构造称为try-with-resources语句. 完成这项工作的机制称为AutoClosea ...

  3. powerbi服务器 试用 无限,超级福利中国版PowerBI高级个人版现已开通,从零免费无限试用法泄露...

    他来了,且已登陆中国.Power BI Premium Per User 现已彻底完全登陆中国,这意味着:自助式商业智能分析,其范围和能力将在国内扩大到前所未有的广度,我们也将用一系列文章带您从零成为 ...

  4. 数据资源 | 八大板块!数据公开下载渠道(下)

    本文综合整理自网站企研·中国学术大数据平台(https://r.qiyandata.com) 来源:企研·中国学术大数据平台 | 公共数据资源 前文回顾:数据资源 | 八大板块!数据公开下载渠道(上) ...

  5. 数据资源 | 八大板块!数据公开下载渠道(中)

    本文综合整理自网站企研·中国学术大数据平台(https://r.qiyandata.com) 来源:企研·中国学术大数据平台 | 公共数据资源 前文回顾:数据资源 | 八大板块!数据公开下载渠道(上) ...

  6. 数据资源 | 八大板块!数据公开下载渠道

    本文综合整理自网站企研·中国学术大数据平台(https://r.qiyandata.com) 来源:企研·中国学术大数据平台 | 公共数据资源 目录 三农 地理信息 生态环境 碳中和 调查数据 省级统 ...

  7. java java se_Java SE 9:尝试资源改进

    java java se 发表简要目录: (Post Brief Table of Content:) Introduction介绍 Java SE 7: Try-With-Resources Bas ...

  8. 文档资源推荐 研究生如何做文献阅读笔记(强力推荐!!!)

    转自:http://www.soudoc.com/bbs/viewthread.php?tid=9056542&extra=&page=1 研究生如何做文献阅读笔记? 说实在的,我自己 ...

  9. Qt下对软件试用期以及使用次数设置

    Qt下对软件试用期以及使用次数设置 利用注册表和配置文件限制用户对软件的使用次数和天数. https://blog.csdn.net/qq_24282081/article/details/97259 ...

最新文章

  1. 真正的在线教育,开始萌芽了
  2. java浏览器实验报告_关于java实验报告模板
  3. 设计模式(2): 观察者模式-1
  4. Git 技术篇 - Github在项目分支里下载某个文件方法,Github项目里的单个js文件下载实例演示
  5. flutter 实现不可滚动的ListView构建器
  6. 五十八、如何对一个数进行分解质因数
  7. OpenGL反射和折射
  8. tomcat内存溢出(修改catalina.bat后windows启动tomcat服务没有效果) | 王猛的个人主页...
  9. 如何做一个国产数据库系统(一)
  10. 数据结构 队列Queue
  11. Harmony OS — Image图片
  12. |app自动化测试之Appium 原理 与 JsonWP 协议分析
  13. 十折交叉验证 matlab,Matlab 十折交叉验证
  14. pipreqs 命令 ConnectionResetError(10054, ‘An existing connection was forcibly closed by the remote hos
  15. 2016.8.26 动态规划及杂题选讲 [树形dp] [数论] [矩阵快速幂]
  16. Java枚举—枚举进阶
  17. php rewind函数,函数rewind的作用是什么
  18. mysql占用CPU过高解决
  19. 求职迷茫?看看这篇为你准备的求职指北吧!
  20. 贝茨视觉训练法 [20160316]

热门文章

  1. python3.6 +tkinter GUI编程 实现界面化的文本处理工具
  2. Software--Architecture--SOA 面向服务体系结构
  3. C#部分类与部分方法
  4. WordPress 在function.php 文件中方法中the_XXX方法失效
  5. ASP.NET MVC5+EF6+EasyUI 后台管理系统(28)-系统小结
  6. C语言的关键字 详解
  7. 做运动(Dijkstra+并查集+MST)
  8. IK Analyzer 中文分词器
  9. 查询结果做缓存的例子
  10. 前端笔记 | CSS进阶