现在我在第 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 block 造成的。
它可能会由于位于 try block 中而错过初始化,从而导致错误?
最佳答案
问题是您根本没有初始化FileInputStream fin
。对于编译器来说,您的代码将如下所示:
FileInputStream fin;
try {
fin = ...
//more code goes here...
} catch (...) {
//exception handling...
} finally {
fin.close(); //fin is not even null for the compiler
}
为了使代码正常工作,请至少使用 null
值对其进行初始化,并在使用 close
之前检查是否 fin != null
> 方法。
FileInputStream fin = null;
try {
fin = ...
//more code goes here...
} catch (...) {
//exception handling...
} finally {
if (fin != null) {
fin.close(); //fin is not null, at least the JVM could close it
}
}
更多信息:
关于java - 流对象初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13328536/