FileNotFoundException in Java – Java中的FileNotFoundException

最后修改: 2016年 10月 7日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

In this article, we’re going to talk about a very common exception in Java – the FileNotFoundException.

在这篇文章中,我们将讨论Java中一个非常常见的异常–FileNotFoundException

We’ll cover the cases when it can occur, possible ways of treating it and some examples.

我们将介绍可能发生的情况,可能的治疗方法和一些例子。

2. When Is the Exception Thrown?

2.何时抛出异常?

As indicated on Java’s API documentation, this exception can be thrown when:

正如Java的API文档所指出的,这个异常在以下情况下会被抛出。

  • A file with the specified pathname does not exist
  • A file with the specified pathname does exist but is inaccessible for some reason (requested writing for a read-only file, or permissions don’t allow accessing the file)

3. How to Handle It?

3.如何处理?

First of all, taking into account that it extends java.io.IOException that extends java.lang.Exception, you will need to deal with it with a try-catch block as with any other checked Exception.

首先,考虑到它扩展了java.io.IOException,扩展了java.lang.Exception,你将需要用try-catch块来处理它,就像处理其他被检查的Exception一样。

Then, what to do (business/logic related) inside the try-catch block actually depends on what you need to do.

然后,在try-catch块内做什么(业务/逻辑相关)实际上取决于你需要做什么。

You may need to:

你可能需要。

  • Rise a business-specific exception: this may be a stop execution error, but you will leave the decision in the upper layers of the application (don’t forget to include the original exception)
  • Alert a user with a dialogue or error message: this isn’t a stop execution error, so just notifying is enough
  • Create a file: reading an optional configuration file, not finding it and creating a new one with default values
  • Create a file in another path: you need to write something and if the first path is not available, you try with a fail-safe one
  • Just log an error: this error should not stop the execution but you log it for future analysis

4. Examples

4.例子

Now we’ll see some examples, all of which will be based on the following test class:

现在我们将看到一些例子,所有这些例子都将基于以下测试类。

public class FileNotFoundExceptionTest {

    private static final Logger LOG
      = Logger.getLogger(FileNotFoundExceptionTest.class);
    private String fileName = Double.toString(Math.random());
    
    protected void readFailingFile() throws IOException {
        BufferedReader rd = new BufferedReader(new FileReader(new File(fileName)));
        rd.readLine();
        // no need to close file
    }

    class BusinessException extends RuntimeException {
        public BusinessException(String string, FileNotFoundException ex) {
            super(string, ex);
        }
    }
}

4.1. Logging the Exception

4.1.记录异常情况

If you run the following code, it will “log” the error in the console:

如果你运行以下代码,它将在控制台中 “记录 “错误。

@Test
public void logError() throws IOException {
    try {
        readFailingFile();
    } catch (FileNotFoundException ex) {
        LOG.error("Optional file " + fileName + " was not found.", ex);
    }
}

4.2. Raising a Business Specific Exception

4.2.提出一个特定业务的例外情况

Next, an example of raising a business-specific exception so that the error can be handled in the upper layers:

接下来,举个例子,提出一个特定业务的异常,以便在上层处理错误。

@Test(expected = BusinessException.class)
public void raiseBusinessSpecificException() throws IOException {
    try {
        readFailingFile();
    } catch (FileNotFoundException ex) {
        throw new BusinessException(
          "BusinessException: necessary file was not present.", ex);
    }
}

4.3. Creating a File

4.3.创建一个文件

Finally, we’ll try to create the file so it can be read (maybe for a thread that is continuously reading a file), but again catching the exception and handling the possible second error:

最后,我们将尝试创建文件,这样它就可以被读取了(也许对于一个正在持续读取文件的线程来说),但还是要捕捉异常并处理可能出现的第二个错误。

@Test
public void createFile() throws IOException {
    try {
        readFailingFile();
    } catch (FileNotFoundException ex) {
        try {
            new File(fileName).createNewFile();
            readFailingFile();            
        } catch (IOException ioe) {
            throw new RuntimeException(
              "BusinessException: even creation is not possible.", ioe);
        }
    }
}

5. Conclusion

5.结论

In this quick writeup, we’ve seen when a FileNotFoundException can occur and several options to handle it.

在这篇快速的文章中,我们看到了什么时候会出现文件未找到异常以及处理它的几个选项。

As always, the full examples are over on Github.

一如既往,完整的示例在Github上