如何在Try/Catch块之前初始化InputStream

2022-04-09 00:00:00 initialization java inputstream

我需要获取文件名字符串,然后尝试打开该文件。如果找不到该文件,我将进行循环,直到输入正确的字符串。

public static void main(String[] args){

// Get file string until valid input is entered.
System.out.println("Enter file name.
 Enter ';' to exit.");
String fileName = sc.nextLine();
boolean fileLoop = true;
InputStream inFile;

while (fileLoop){
    try{
        inFile = new FileInputStream(fileName);
        fileLoop = false;
    } catch (FileNotFoundException e) {
        System.out.println("That file was not found.
 Please re enter file name.
 Enter ';' to exit.");
        fileName = sc.nextLine();
        if (fileName.equals(";")){
            return;
        }
   } 

}

// ****** This is where the error is. It says inFile may not have been initalized. ***
exampleMethod(inFile);
}

public static void exampleMethod(InputStream inFile){

    // Do stuff with the file.
}

当我尝试调用exampleMethod(InFile)时,NetBeans告诉我InputStream inFile可能尚未初始化。我认为这是因为赋值位于try Catch块内。正如大家所看到的,我尝试在循环外部声明对象,但没有成功。

我还尝试使用以下内容在循环外部初始化输入流:

InputStream inFile = new FileInptStream();
// This yeilds an eror because there are no arguments.

还有这个:

InputStream inFile = new InputStream();
// This doesn't work because InputStream is abstract.

如何确保在初始化此InputStream的同时仍允许循环,直到输入有效输入?

谢谢


解决方案

要修复此问题,请更改以下代码行:

InputStream inFile;

至此:

InputStream inFile = null;
您必须这样做的原因是Java阻止您使用未初始化的局部变量。使用未初始化的变量通常是一个疏忽,因此Java不允许在此场景中使用它。正如@immibis指出的那样,这个变量将始终被初始化,但编译器在这种情况下不够聪明,无法计算出它。

相关文章