Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7a72cbc

Browse files
[feat] Improve content description of try-with-resources
1 parent 3c2d4ab commit 7a72cbc

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

‎docs/java/Java基础知识.md‎

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

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /