【问题标题】:How to Initialize an InputStream Before Try/Catch Block如何在 Try/Catch 块之前初始化 InputStream
【发布时间】:2015-02-18 21:26:34
【问题描述】:

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

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 块内。如您所见,我尝试在循环之外声明对象,但没有奏效。

我还尝试使用以下方法在循环外初始化输入流:

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 的同时仍允许循环,直到输入有效输入?

谢谢

【问题讨论】:

  • 请注意,它始终初始化的,但编译器不够聪明,无法知道这一点。
  • 在这种情况下使用new File(fileName).canRead()作为循环条件会更合适。
  • @immibis 你能具体点吗?我觉得我看到了一条未初始化的路径。
  • @DanielKaplan 注意到fileLoop 只能在分配inFile 后变为假...假设file1LoopfileLoop 的拼写错误。
  • 是 file1Loop 是一种类型,现在已修复。

标签: java initialization inputstream


【解决方案1】:

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

InputStream inFile;

到这里:

InputStream inFile = null;

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

【讨论】:

  • 太棒了,这成功了。以为这很简单。谢谢。
  • 使用while (inFile == null)条件确保文件打开成功。
  • 不要忘记在finally 块中关闭流!
  • 是的,我知道必须进行一些初始化才能使编译器满意,即使在逻辑上它不会退出 while 循环,除非对象已初始化。我是 Java 新手,我觉得这很有趣。
猜你喜欢
  • 1970-01-01
  • 2014-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-23
  • 2021-08-09
  • 2016-08-18
相关资源
最近更新 更多