try-with-resources
try-with-resources
AC ac = null;
AC2 ac2 = null;
try {
ac = new AC();
ac2 = new AC2();
} catch (Exception e) {
} finally {
ac.close();
ac2.close();
}
try (AC ac = new AC();
AC2 ac2 = new AC2()) {
} catch (Exception e) {
}
可以很明显的看到,
IO 案例
private static void printFile() throws IOException {
InputStream input = null;
try{
input = new FileInputStream("d:\\hello.txt");
int data = input.read();
while(data != -1){
System.out.print((char) data);
data = input.read();
}
} finally {
if(input != null){
input.close();
}
}
}
以上程序
假设
private static void printFileJava7() throws IOException {
try(FileInputStream input = new FileInputStream("d:\\hello.txt")) {
int data = input.read();
while(data != -1){
System.out.print((char) data);
data = input.read();
}
}
}
这就是
当
当
AutoCloseable
public class AC implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("Program has been closed pretended.");
}
//默认静态方法,在被实例化时执行
static {
System.out.println("Program running.");
}
}
public class AC2 implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("Program 2 has been closed pretended.");
}
static {
System.out.println("Program 2 running.");
}
}
public class Main {
public static void main(String[] args) {
try (AC ac = new AC();
AC2 ac2 = new AC2()) {
//这里假装执行了有用的代码
Thread.sleep(2000);
} catch (Exception e) {
}
}
}