-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathExample1.java
More file actions
71 lines (60 loc) · 1.94 KB
/
Example1.java
File metadata and controls
71 lines (60 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package javatips.exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* 在 Finally 中清理资源,或者使用 Try-With-Resource 语句
*
* @author biezhi
* @date 2018/9/18
*/
public class Example1 {
private static final Logger log = LoggerFactory.getLogger(Example1.class);
public void doNotCloseResourceInTry() {
FileInputStream inputStream = null;
try {
File file = new File("./王爵的私有宝贝.txt");
inputStream = new FileInputStream(file);
// 使用 inputStream 读取文件内容
// 兄弟,不要这么做
inputStream.close();
} catch (FileNotFoundException e) {
log.error("", e);
} catch (IOException e) {
log.error("", e);
}
}
public void closeResourceInFinally() {
FileInputStream inputStream = null;
try {
File file = new File("./王爵的私有宝贝.txt");
inputStream = new FileInputStream(file);
// 使用 inputStream 读取文件内容
} catch (FileNotFoundException e) {
log.error("", e);
} catch (IOException e) {
log.error("", e);
} finally {
if(null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
log.error("关闭流失败", e);
}
}
}
}
public void autoCloseResource() {
File file = new File("./王爵的私有宝贝.txt");
try (FileInputStream inputStream = new FileInputStream(file)){
// 使用 inputStream 读取文件内容
} catch (FileNotFoundException e) {
log.error("", e);
} catch (IOException e) {
log.error("", e);
}
}
}