如何在 Try/Catch 块之前初始化输入流

Mal*_*nge 2 java initialization inputstream

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

public static void main(String[] args){

// Get file string until valid input is entered.
System.out.println("Enter file name.\n 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.\n Please re enter file name.\n 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.
}
Run Code Online (Sandbox Code Playgroud)

当我尝试调用 exampleMethod(inFile) 时,NetBeans 告诉我 InputStream inFile 可能尚未初始化。我认为这是因为分配位于 try catch 块内。正如您所看到的,我尝试在循环之外声明该对象,但这不起作用。

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

InputStream inFile = new FileInptStream();
// This yeilds an eror because there are no arguments.
Run Code Online (Sandbox Code Playgroud)

还有这个:

InputStream inFile = new InputStream();
// This doesn't work because InputStream is abstract.
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Dan*_*lan 5

要解决此问题,请更改这行代码:

InputStream inFile;
Run Code Online (Sandbox Code Playgroud)

对此:

InputStream inFile = null;
Run Code Online (Sandbox Code Playgroud)

必须这样做的原因是 Java 阻止您使用未初始化的局部变量。使用未初始化的变量通常是一种疏忽,因此 Java 不允许在这种情况下使用它。正如 @immibis 指出的,这个变量总是会被初始化,但编译器不够聪明,无法在这种情况下弄清楚它。