1
0
mirror of https://github.com/Snailclimb/JavaGuide synced 2025-06-16 18:10:13 +08:00

[feat] Improve content description of try-with-resources

This commit is contained in:
guide 2020-07-31 21:00:09 +08:00
parent 3c2d4ab28e
commit 7a72cbca06

View File

@ -1239,9 +1239,12 @@ public class Test {
#### 3.2.4. 使用 `try-with-resources` 来代替`try-catch-finally`
1. **适用范围(资源的定义):** 任何实现 `java.lang.AutoCloseable`或者``java.io.Closeable` 的对象
2. **关闭资源和final的执行顺序**`try-with-resources` 语句中,任何 catch 或 finally 块在声明的资源关闭后运行
《Effecitve Java》中明确指出
> 面对必须要关闭的资源我们总是应该优先使用try-with-resources而不是`try-finally`。随之产生的代码更简短,更清晰,产生的异常对我们也更有用。`try-with-resources`语句让我们更容易编写必须要关闭的资源的代码,若采用`try-finally`则几乎做不到这点。
> 面对必须要关闭的资源,我们总是应该优先使用 `try-with-resources` 而不是`try-finally`。随之产生的代码更简短,更清晰,产生的异常对我们也更有用。`try-with-resources`语句让我们更容易编写必须要关闭的资源的代码,若采用`try-finally`则几乎做不到这点。
Java 中类似于`InputStream``OutputStream``Scanner``PrintWriter`等的资源都需要我们调用`close()`方法来手动关闭,一般情况下我们都是通过`try-catch-finally`语句来实现这个需求,如下:
@ -1276,7 +1279,20 @@ try (Scanner scanner = new Scanner(new File("test.txt"))) {
当然多个资源需要关闭的时候,使用 `try-with-resources` 实现起来也非常简单,如果你还是用`try-catch-finally`可能会带来很多问题。
通过使用分号分隔,可以在`try-with-resources`块中声明多个资源:
通过使用分号分隔,可以在`try-with-resources`块中声明多个资源。
```java
try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")))) {
int b;
while ((b = bin.read()) != -1) {
bout.write(b);
}
}
catch (IOException e) {
e.printStackTrace();
}
```
### 3.3. 多线程