문제

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?
도움이 되었습니까?

해결책

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

다른 팁

You should use the .ready() method.

String line;
while(reader.ready())
{
    line = reader.readLine();
    ....
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top