-1

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?
Vlad Schnakovszki
  • 8,434
  • 6
  • 80
  • 114

2 Answers2

0

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

Girish
  • 1,717
  • 1
  • 18
  • 30
-1

You should use the .ready() method.

String line;
while(reader.ready())
{
    line = reader.readLine();
    ....
}
Hannes
  • 2,018
  • 25
  • 32
  • No, ready() shouldn't be used. The while loop of the OP is the right way to read all lines from a reader. – JB Nizet Feb 02 '14 at 14:14
  • @JBNizet can you please explain your comment, since afaik using ready is the way to do it. – Hannes Feb 02 '14 at 14:23
  • `ready()` is basically useless. If it returns true, then the next call to `read()` (not `readLine()`) is guaranteed not to block. If it returns false, then you just don't have any guarantee. An implementation of Reader is free to always return false. Reading the lines until readLine() returns null, OTOH, is guaranteed to read every line from the reader. – JB Nizet Feb 02 '14 at 15:17
  • @JBNizet Not using ready can result in a blocking read. This will cause service downs. I had many production bugs on my desk caused by not checking, if the stream is ready. Null will only be returned if no more data is available from the stream. If you read the line and no new line is in the buffer, the readline method will block until more data is received. – Hannes Feb 02 '14 at 16:08