Question

I have to create a reader and to catch an exception if a file cannot be read. The code is something like this:

String line;
try {
    while ((line = reader.readLine()) != null) {
    //DO SOMETHING
    }
} catch (IOException e) {
    System.out.println("IO operation failed.");
    e.printStackTrace();
}

I've got 2 questions:

  1. Is this code ok?
  2. How can i make an "unreadable" file to test the code?
Was it helpful?

Solution

you will get the exception if the file is not found, there can be a case that you have not created the file or you have deleted it from that you are reading or there can be other IOException

  java.io.IOException
          |
          |
   java.io.FileNotFoundException

as FileNotFoundException is the child of java.io.IOException

OTHER TIPS

You should use the .ready() method.

String line;
while(reader.ready())
{
    line = reader.readLine();
    ....
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top