我试图用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());奇怪的是,有时它有效,有时它不会,所以没有线可以得到。
发布于 2015-05-26 15:33:08
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
}https://stackoverflow.com/questions/30462781
复制相似问题