这段代码来自oracle i / o tutorial:
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");
答案 0 :(得分:3)
您需要在in
之外声明out
和try {...}
,因为您需要在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) {...}
}
答案 1 :(得分:1)
如果在try块中声明并初始化流,在finally语句中如果要尝试关闭流,则编译器不知道中的值是什么,< strong> 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();
}
}
答案 2 :(得分:0)
因为输入流是一种沉重的资源 您已经打开了一个FileInputStream,现在在使用它时会发生一些异常。 然后该流将继续打开,浪费资源。
所以你在try块之前用null初始化它,这样你就可以在finally块中关闭它,即正确的方法来清理资源。
FileInputStream in=null
try{
}catch(IOException ioexcep){
}
finally {
in.close;
}
答案 3 :(得分:0)
如果您使用的是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块完成或抛出异常时它将关闭()。