In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "the usage scenario and practical application of try-with-resources in java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "the usage scenario and practical application of try-with-resources in java".
1. At the beginning, the actual try-with-resources uses the following: / * read out binary files * * @ param filePath text absolute path * @ return * @ throws FileNotFoundException * @ throws IOException * / public static byte [] getReaderToBinary (String filePath) throws FileNotFoundException, IOException {int bufferSize = 4096; / / set buffer size byte buffer [] = new byte [bufferSize] / / buffer byte array File sourceFile = new File (filePath); byte [] b = null; try (InputStream fis = new FileInputStream (sourceFile); BufferedInputStream bis = new BufferedInputStream (fis, bufferSize);) {int len = bis.available (); b = new byte [len]; bis.read (b, 0, len) } return b;}
The reference address for the above example is:
* author: this person is too lazy * Source: CSDN * original: https://blog.csdn.net/qq_35546153/article/details/83421506 * copyright notice: this article is the original article of the blogger, please attach a link to the blog article to reprint it!
Previously, using try-catch-finally was more cumbersome and unintuitive, and even occasionally forgot to turn it off, as follows:
InputStream fis = null; BufferedInputStream bis = null; try {fis = new FileInputStream (sourceFile); bis = new BufferedInputStream (fis, bufferSize); int len = bis.available (); b = new byte [len]; bis.read (b, 0, len);} finally {if (fis! = null) {fis.close () } if (bis! = null) {bis.close ();}} 2, usage scenario
The use of try-with-resources is to define the resources that need to be closed in parentheses after the try keyword. Resources are automatically released after the try block is executed.
It is important to note, however, that not all code that is expected to be closed can be put into it, and only classes that implement the java.lang.AutoCloseable interface can be closed automatically.
Eg: InputStream in the above code example, which is defined as follows:
Public abstract class InputStream implements Closeable
And Closeable, which is defined as follows (from jdk1.5 version):
/ * * 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
Description:
1. Try-with-resource syntax is added since JDK7.
2. It's just a syntactic sugar: when you decompile the above code, you will find that for the JVM virtual machine, it still sees the previous try-catch-finally writing.
3. Practical use
Most of the scenes are opened with external resources:
File
Database connection
Network connection
Etc.
If there are custom requirements:
Public class CustomResource implements java.lang.AutoCloseable {@ Override public void close () {System.out.printf ("close method of [% s] called\ n", this.getClass (). GetName ());} public static void main (String [] args) {try (CustomResource customResource = new CustomResource ();) {/ / do something System.out.println ("do something") Throw new RuntimeException ("Test throws an unknown exception");}
The console output is as follows:
Do somethingException in thread "main" java.lang.RuntimeException: test throws an unknown exception at com.xxx.main (CustomResource.java:22) calls the close method of [com.xxx.CustomResource]
Note: even if an exception is thrown in the try block, it does not affect the shutdown of the resource
4. Other key points
Note:
Public class CustomResource implements java.lang.AutoCloseable {public CustomResource () {throw new RuntimeException ("Constructor exception:" + this.getClass () .getName ());} @ Override public void close () {System.out.printf ("close method of [% s] called\ n", this.getClass () .getName ()); throw new RuntimeException ("close method exception:" + this.getClass () .getName () } public static void main (String [] args) {try (CustomResource customResource = new CustomResource ();) {/ / do something System.out.println ("do something");} catch (Exception e) {System.out.println ("do catch"); e.printStackTrace ();}
The console output is as follows:
Do catchjava.lang.RuntimeException: constructor exception: com.xxx.CustomResource at com.xxx.CustomResource. (CustomResource.java:13) at com.xxx.CustomResource.main (CustomResource.java:24)
Explanation (reference address: https://www.cnblogs.com/itZhy/p/7636615.html):
During try-with-resource, if both the handling of external resources and the closure of external resources encounter exceptions, the "close exception" will be suppressed and the "handle exception" will be thrown, but the "close exception" will not be lost, but will be stored in the list of suppressed exceptions in the "handling exception".
At this point, I believe you have a deeper understanding of the "use scenarios and practical applications of try-with-resources in java". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.