How to Initialize an InputStream Before Try/Catch Block
initialization, inputstream, java
Solution
To fix this, change this line of code:
InputStream inFile;
to this:
InputStream inFile = null;
The reason you have to do this is because Java prevents you from using local variables that are uninitialized. Using an uninitialized variable is often an oversight, so Java prevents it from being allowed in this scenario. As @immibis pointed out, this variable will always be initialized, but the compiler isn't smart enough to figure it out in this case.
Problem
I need to get a file name string, and try to open the file. If the file is not found, I loop until a proper string is entered. ``` 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. } ``` When I try to call exampleMethod(inFile) NetBeans tells me that the InputStream inFile may not have been initialized. I assume this is because the assignment is within a try catch block. As one can see, I tried declaring the object outside of the loop and that did not work. I also tried initializing the input stream outside of the loop with the following: ``` InputStream inFile = new FileInptStream(); // This yeilds an eror because there are no arguments. ``` and this as well: ``` InputStream inFile = new InputStream(); // This doesn't work because InputStream is abstract. ``` How do I ensure that I initalize this InputStream while still allowing for looping until valid input is entered? Thank You