如何在 Try/Catch 块之前初始化 InputStream
How to Initialize an InputStream Before Try/Catch Block
我需要获取文件名字符串,并尝试打开文件。如果找不到文件,我将循环直到输入正确的字符串。
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 的同时仍允许循环直到输入有效输入?
谢谢
要解决此问题,请更改这行代码:
InputStream inFile;
对此:
InputStream inFile = null;
您必须这样做的原因是 Java 阻止您使用未初始化的局部变量。使用未初始化的变量通常是一种疏忽,因此 Java 阻止它在这种情况下被允许。正如@immibis 指出的那样,这个变量总是会被初始化,但编译器不够聪明,无法在这种情况下弄清楚。
我需要获取文件名字符串,并尝试打开文件。如果找不到文件,我将循环直到输入正确的字符串。
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 的同时仍允许循环直到输入有效输入?
谢谢
要解决此问题,请更改这行代码:
InputStream inFile;
对此:
InputStream inFile = null;
您必须这样做的原因是 Java 阻止您使用未初始化的局部变量。使用未初始化的变量通常是一种疏忽,因此 Java 阻止它在这种情况下被允许。正如@immibis 指出的那样,这个变量总是会被初始化,但编译器不够聪明,无法在这种情况下弄清楚。