I'm trying to initialize an InputStream
, but it is not allowing me. I have been able to initialize OutputStream
.
public void readData() {
String fileName = "clinicData.txt";
Scanner inputStream;
System.out.println("The file " + fileName +"\ncontains the following line:\n");
try {
inputStream = new Scanner (new File (fileName));
} catch (FileNotFoundException e) {
System.out.println("Error: opening the file " +fileName);
System.exit(0);
}
while (inputStream.hasNextLine()) {
String line = inputStream.nextLine();
System.out.println (line);
}
inputStream.close();
}
The code above is the section I am working with if you need me to post the other section with the outputStream just tell me.
You want to do this:
try (Scanner inputStream = new Scanner(new File(fileName))) {
while (inputStream.hasNextLine()) {
String line = inputStream.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("Error: opening the file " +fileName);
System.exit(0);
}
Scanner inputStream;
is initialized in the try
block, however, it is not guaranteed the initialization succeeds and you would try to access such instance in the while
loop later, which would be erroneous. Move the while
loop inside the try
block.Scanner
is AutoCloseable
, hence you can use try-with-resources and omit inputStream.close()