在try 语句块内实例化的文件字节流对象,在finally语句块内为何无法解析?


try {
        f1=new File("data.txt");//data已存在     
        f2=new File("b.txt");//File只是创建了一个指向文件的对象,并未在磁盘写入。f2是写入对象
        f2.createNewFile(); 
        //FileInputStream fInput = null;
        //FileOutputStream fOut = null; 
        FileInputStream fInput = new FileInputStream(f1);
        FileOutputStream fOut = new FileOutputStream(f2);
        fInput.read(b1);
        fOut.write(b1);//覆写文件。
        } 
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                if(fInput!=null){//此处提示“fInput cannot be resolved to a variable”
                    fInput.close();
                } 
                }

经多次测试,只有在try语句块外面加入

        FileInputStream fInput = null;
        FileOutputStream fOut = null;

才不会导致错误。
感谢各位。

因为你是在try内定义的变量,是局部变量,其作用域只在try内有效,就类似你在if内定义的变量一样,其作用域只在if的花括弧内有效一样

https://blog.csdn.net/wisgood/article/details/19505051