【发布时间】: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后变为假...假设file1Loop是fileLoop的拼写错误。 -
是 file1Loop 是一种类型,现在已修复。
标签: java initialization inputstream