getClassLoader()。getResource()抛出NullPointerException吗?为什么不出现FileNotFoundException?

The*_*Guy 3 java io file nullpointerexception

我正在尝试在正在处理的程序中加载文件。我通过使用getClassLoader()。getResource()来做到这一点。能够找到该文件时,此方法非常适用。但是,当找不到文件时,它将引发NullPointerException。它不应该抛出FileNotFoundException,或者getResource()不会抛出此类异常吗?

这是代码(相当标准的文件加载):

public static File loadFile(String path) throws FileNotFoundException
{
    return new File(FileHandler.class.getClassLoader().getResource(path).getFile());
}

//somewhere else
loadFile("data/xt.txt");
Run Code Online (Sandbox Code Playgroud)

如果xt.txt存在,则代码可以正常工作。如果不是,则抛出NullPointerException。我可以轻松地修改代码以处理NullPointerException,但我无法想到为什么它首先返回null而不是FileNotFound。

use*_*751 5

getResource 不会抛出异常。null如果找不到资源,则返回。

您的代码尝试调用getFile由返回的空引用时,将引发异常getResource

您可以这样做:

URL resourceURL = FileHandler.class.getClassLoader().getResource(path);
if(resourceURL == null)
    throw new FileNotFoundException(path+" not found");
return new File(resourceURL.getFile());
Run Code Online (Sandbox Code Playgroud)