我正在尝试执行这段代码,我也提供了有效的参数,但我仍然在第 1 行遇到错误。 34 和 35 表明局部变量 fin 和 fout 可能尚未初始化。如何解决这个问题在此处输入代码
package maxbj.myTest.p1;
import java.io.*;
public class CopyFile {
public static void main(String[] args)throws IOException {
int i;
FileInputStream fin;
FileOutputStream fout;
try{
//trying to open input file
try{
fin=new FileInputStream(args[0]);
}catch(FileNotFoundException e){
System.out.println("Input file not found");
return;
}
//trying to open output file
try{
fout=new FileOutputStream(args[1]);
return;
}catch(FileNotFoundException e){
System.out.println("Output file cannot be opened or created");
return;
}
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index out of bound exception");
}
//code to copy file
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();
}
}
PS-这段代码来自《JAVA COMPLETE REFRENCE》一书
最佳答案
编译器是正确的(而这本书是错误的,他们应该在出版前尝试编译他们的代码):当 fin
在代码到达fin.read()
行。
具体来说,如果 ArrayIndexOutOfBoundsException
在第一个外部 try
/catch
block 中被抛出,fin
变量将不被分配。将 return
添加到外部 catch
block 应该可以解决此问题:
try {
...
} catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index out of bound exception");
return; // <<== Here
}
有了 return
语句,控制永远不会到达 fin.read()
除非 fin
已经初始化,修复编译-时间错误。
关于java - 在 try block 内,FileIStream 变量可能尚未初始化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16196384/