문제

What kind of problem may occur for this code? I think even exception occurs, this code can throw the exception to its caller. So it does NOT generate any trouble.

How can I improve it?

public static void cat(File named) {
  RandomAccessFile input = null;
  String line = null;
  try {
    input = new RandomAccessFile(named, “r”);
    while ((line = input.readLine()) != null {
      System.out.println(line);
    }
    return;
  } finally {
    if (input != null) {
      input.close();
    }
  }
}
도움이 되었습니까?

해결책 2

What kind of problem may occur for this code?

Since public class FileNotFoundException extends IOException

You can change your method to:

public static void cat(File named) throws IOException

And now you don't need a try-catch blocks.

And the caller should catch the exception thrown by the method.

But why don't you want to catch the exceptions?

다른 팁

The code has to throw the IOException - try editing your code with eclipse and you would also get a suggestion to throw the Exception.

Also Java 1.7 has the new concept of "try-with-resources" - see the try statement below. The resource used in try (...) is closed automatically.

public static void cat(File named) throws IOException
{
    try (RandomAccessFile input = new RandomAccessFile(named, "r"))
    {
        String line = null;
        while ((line = input.readLine()) != null)
        {
            System.out.println(line);
        }
    }
}

add the throws declaration in your method , and then caller of this method should have try catch block for this exception .

public static void cat(File named) throws IOException {
      RandomAccessFile input = null;
      String line = null;
      try {
        input = new RandomAccessFile(named, "r");
        while ((line = input.readLine()) != null ){
          System.out.println(line);
        }
        return;
      } finally {
        if (input != null) {
          input.close();
        }
      }
    }
  //caller 
   try{
     Class.cat(new File("abc.txt"));
    }catch(IOException e)
    {
      //
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top