这段来自oracle i/o教程的代码:
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
为什么这些线路
FileInputStream in = null;
FileOutputStream out = null;
不包括以这种方式尝试块(没有= null
)?
FileInputStream in = new FileInputStream("xanadu.txt");
FileOutputStream out = new FileOutputStream("outagain.txt");
您需要在try {...}
之外声明in
和out
,因为您需要关闭finally {...}
块中的这些资源。
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
....
} catch(Exception e) {
} finally {
try {
if(in != null) {
in.close();
}
if(out != null) {
out.close();
}
catch(Exception e) {...}
}
如果在try {...}
的作用域内声明它们,编译器将抱怨它们无法解析。
如果你这样做:
try {
FileInputStream in = new FileInputStream("xanadu.txt");
FileOutputStream out = new FileOutputStream("outagain.txt");
int c;
....
} catch(Exception e) {
} finally {
try {
if(in != null) { //in could not be resolved error by compiler
in.close();
}
if(out != null) { //out could not be resolved...
out.close();
}
catch(Exception e) {...}
}
如果您在try块内声明并初始化流,在finally语句中,如果您想尝试关闭流,编译器不知道关闭流的in和out的值是什么。
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
} catch(Exception e) {
----
} finally {
if(in!=null) {
in.close();
}
if(out!= null) {
out.close();
}
}
因为Inputstream是一个繁重的资源
您已经打开了一个FileInputStream,现在在使用它时出现了一些异常。然后,这条溪流将继续开放,浪费资源。
所以你在try块之前用null初始化它,这样你就可以在finally块中关闭它,即清理资源的正确方法。
FileInputStream in=null
try{
}catch(IOException ioexcep){
}
finally {
in.close;
}
如果您使用的是Java 7或更好的版本,您可以使用try with resources,它将为您处理关闭。
try(
FileInputStream in = new FileInputStream("xanadu.txt");
FileOutputStream out = new FileOutputStream("outagain.txt");
) {
.... do stuff
} catch (Exception e) {
... deal with the exception
};
这是因为FileInputStream实现了java.lang.AutoCloseable,所以当try块完成或抛出异常时,它将关闭()。