Java 在try块内,FileIStream变量可能未初始化错误
我试图执行这段代码,同时也提供了有效的参数,但仍然在第34行和第35行出现错误,即局部变量fin和fout可能尚未初始化。如何解决此问题Java 在try块内,FileIStream变量可能未初始化错误,java,try-catch,fileinputstream,fileoutputstream,Java,Try Catch,Fileinputstream,Fileoutputstream,我试图执行这段代码,同时也提供了有效的参数,但仍然在第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; FileOu
在此处输入代码
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完全引用》一书。编译器是对的(而这本书是错的,他们应该在发布之前尝试编译代码):当代码到达fin.read()
行时,fin
保持未初始化状态时,代码中有一条路径
具体来说,如果在第一个外部try
/catch
块中抛出ArrayIndexOutOfBoundsException
异常,则不会分配fin
变量。将return
添加到外部catch
块应该可以解决此问题:
try {
...
} catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index out of bound exception");
return; // <<== Here
}
试试看{
...
}捕获(阵列索引边界外异常e){
System.out.println(“数组索引越界异常”);
return;//解决这个问题的一个简单方法是在try块中执行任何需要fin和fout的操作。这样,当流在打开时失败时,您将永远不会尝试使用它们
try
{
fout = new FileOutputStream(...);
fin = new FileInputStream(...);
// Code goes here
fout.close();
fin.close();
}
catch(FileNotFoundException e)
{
// Error code - e should contain the file name/path
}
此外,在声明变量时初始化变量始终是一种良好的做法:
FileOutputStream fout = null;
FileInputStream fin = null;
但是,这种方式(只是初始化为null)编程逻辑不会导致编译器错误,但如果处理不正确,如果尝试块抛出,可能会出现NullPointerException。@SotiriosDelimanolis这不是修复,只是一种解决方法。修复可以确保没有路径未初始化,这是一件相对简单的事情。@SotiriosDelimanolis你可能是对的,很可能OP错过了return
语句。@Sotirios Delimanolis和@dasblinkenlight我对我的错误感到非常抱歉。我犯了一个错误,我写了“return”在初始化FUT后,在试块中,但在发布之后我才意识到我的错误,我真的为我的错误感到抱歉。BijaySijh没关系,每个人都会犯错误。如果这确实是问题,请考虑通过点击复选标记来接受答案。这会让其他人知道你不再寻找一个改进的答案。并在堆栈溢出时为您赢得一枚徽章。@BijaySingh确保您理解错误发生的原因。