Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java getResource上的NullPointerException_Java_File - Fatal编程技术网

Java getResource上的NullPointerException

Java getResource上的NullPointerException,java,file,Java,File,我正在尝试使用SQL语句执行一个文件。唯一的问题是将文件保存到变量文件时,它将生成NullPointerException 代码如下: public DataOpladen(String dataFile) throws IOException { File file = null; try { file = new File(Thread.currentThread().getContextClassLoader().getResource(dataFile)

我正在尝试使用SQL语句执行一个文件。唯一的问题是将文件保存到变量文件时,它将生成NullPointerException

代码如下:

 public DataOpladen(String dataFile) throws IOException {
    File file = null;
    try {
        file = new File(Thread.currentThread().getContextClassLoader().getResource(dataFile).toURI());
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    this.dataSchrijvenNaarDatabase(file);
}
在这一行,我得到了一个例外:

file = new File(Thread.currentThread().getContextClassLoader().getResource(dataFile).toURI());

奇怪的是,它有时能工作,有时不能,因此没有行可获取。

IntelliJ主动警告我,此特定调用可能导致
NullPointerException
,因为
getResource
如果找不到指定的资源,将返回
null

由于如果无法加载所需的资源,您将无法执行任何操作,因此一个简单的修复方法是事先执行空检查:

URL resource = Thread.currentThread().getContextClassLoader().getResource(dataFile);
if(resource != null) {
    file = new File(resource.toURI());
    // rest of program dealing with file here
}

这仍然会给我一个空指针来破坏我的程序。问题是该文件存在于项目的资源中。所以我不明白他为什么会明白,是吗?