java - 如何在 Try/Catch block 之前初始化输入流

标签 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.
}

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

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

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 指出的,这个变量总是会被初始化,但编译器不够聪明,无法在这种情况下弄清楚它。

关于java - 如何在 Try/Catch block 之前初始化输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28594252/

相关文章:

java - 在Java中存储变量类型

java - 如何等待主线程直到AWS S3文件上传完成

.net - 使用 WCF 服务连接到 AppInitialize

c - 对未设置的值使用 IEEE754 浮点 NaN 是个好主意吗?

java - 为什么实例字段的 "int someVal=0"不被视为死代码?

java - URL连接Inputstream和outputstream对象

java - 如何使用 BufferedWriter 和 FileOutPutStream 将数据附加到文件

java - Apache Ignite 查询/索引

java - Jackson XML 在根标签下具有不同的元素名称和属性

Java - 比较两个相同文件的输入流