现在我在第30和38行得到编译时错误,'fin'可能没有被初始化。但它完美地写这种方式流对象初始化
import java.io.*;
class CopyFile {
public static void main(String args[]) throws IOException {
int i;
FileInputStream fin;//can't it be done like this?
FileOutputStream fout= new FileOutputStream(args[1]);
try{
//open input file
try{
fin = new FileInputStream(args[0]);
}
catch(FileNotFoundException e){
System.out.println("Input file Not Found");
return;
}
//open output file
try{
fout = new FileOutputStream(args[1]);
}
catch(FileNotFoundException e){
System.out.println("Error Opening File");
}
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("usage: Copyfile From to");
}
try{
do{
i = fin.read();
if(i!= -1)
fout.write(i);
}while(i != -1);
}
catch(IOException e){
System.out.println("file error");
}
fin.close();
fout.close();
}
}
我已经看到它很多时候像这样初始化。我认为它是由于尝试块。
它可能会错过初始化由于在try块中,因此错误?
如果try块失败,那么'fin'根本就没有被初始化,然后JVM将无法正确关闭它? –
使用一个指向根本没有引用的对象会有问题。这就是为什么编译器将该行标记为错误。在使用它们之前初始化变量是一种很好的做法。 –