java - 在 try block 内,FileIStream 变量可能尚未初始化错误

标签 java try-catch fileinputstream fileoutputstream

我正在尝试执行这段代码,我也提供了有效的参数,但我仍然在第 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/

相关文章:

java - Java中的生产者消费者

java - 带有监视服务和 LastModifiedFileListFilter 的 Spring Integration 文件轮询器

android - 全局捕获所有可能的 android 异常并重新加载应用程序

java - Openfileinput 返回空指针异常

Java读入单个文件并写出多个文件

Java 文件输入流

java - 向数组中的每个元素添加一个外部数字

java - 为什么基本类型有一个 "Class"以及它是如何使用的?

java - 确定编译时多捕获异常类型

c# - 字典 ArgumentException 日志重复键 : which is more performant?