Reputation: 217
I'm trying to declare a BufferedReader in order to read information from a .txt file. I declare it in the following way:
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input-file.txt"))));
Now, I have a small problem with this, because Java complains if I don't declare it in a try/catch block - after all, there's no guarantee the system will find input-file, so I need to catch any IOException thrown. But if I put that declaration in a try-catch block, then Java ALSO complains; I reference br later using the .readLine() method, and since br is declared in a try/catch block, there's no guarantee that BufferedReader will be created. But if I try to take BufferedReader out of the try/catch block to be sure it's created, then I can't catch the IOException...how do I escape this trap?
Upvotes: 2
Views: 876
Reputation: 1089
When you are working with I/O resources java compiler
force you to process unexpected errors which might happen before hand. That is called checked exception
in Java and there is no way to avoid it. So, if you want to read a file, you can do it as follow:
new FileReader("input-file.txt");
If there is no such file it throws FileNotFoundException
and this is checked exception
and compiler force you to process it at compile time. You can decorate it within BufferedReader
:
BufferedReader reader = new BufferedReader(new FileReader("input-file.txt"));
BufferedReader
implements AutoCloseable
interface and you can declare it within try
in try-with-resources
statement as follow:
try (BufferedReader reader = new BufferedReader(new FileReader("input-file.txt"))) { ... }
Compiler will force you to handle FileNotFoundException
and also IOException
. When try
block completes its execution it calls close
method automatically and that method may throw this IOException
, so this is the reason why you should handle it too. So, the complete version might look as follow:
try (BufferedReader reader = new BufferedReader(new FileReader("input-file.txt"))) {
// your logic
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Upvotes: 0
Reputation: 8758
You could read from BufferedReader inside try-catch block:
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input-file.txt"))))) {
String s = br.readLine();
} catch (IOException io) {}
Upvotes: 3