从java1.7开始,java支持自动资源管理,将资源放在try()中,java在执行完之后会自动释放这些资源
前提是这些资源类需要实现 java.lang.AutoCloseable 接口
以下内容来自于http://www.oschina.net/question/12_10706
从 Java 7 build 105 版本开始,Java 7 的编译器和运行环境支持新的 try-with-resources 语句,称为 ARM 块(Automatic Resource Management) ,自动资源管理。
新的语句支持包括流以及任何可关闭的资源,例如,一般我们会编写如下代码来释放资源:
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
|
private
static
void
customBufferStreamCopy(File source, File target) {
InputStream fis =
null
;
OutputStream fos =
null
;
try
{
fis =
new
FileInputStream(source);
fos =
new
FileOutputStream(target);
byte
[] buf =
new
byte
[
8192
];
int
i;
while
((i = fis.read(buf)) != -
1
) {
fos.write(buf,
0
, i);
}
}
catch
(Exception e) {
e.printStackTrace();
}
finally
{
close(fis);
close(fos);
}
}
private
static
void
close(Closeable closable) {
if
(closable !=
null
) {
try
{
closable.close();
}
catch
(IOException e) {
e.printStackTrace();
}
}
}
|
代码挺复杂的,异常的管理很麻烦。
而使用 try-with-resources 语句来简化代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
private
static
void
customBufferStreamCopy(File source, File target) {
try
(InputStream fis =
new
FileInputStream(source);
OutputStream fos =
new
FileOutputStream(target)){
byte
[] buf =
new
byte
[
8192
];
int
i;
while
((i = fis.read(buf)) != -
1
) {
fos.write(buf,
0
, i);
}
}
catch
(Exception e) {
e.printStackTrace();
}
}
|