将数据加载到java时出现NullPointerException。util。属性对象
注意:如果我的英语有错误,请原谅
我在学java!现在我尝试将属性从文件加载到java。util。属性对象。。。
但我有个例外。我通过getClass().getResource("path/to/resource").toFile()
获得filename
,并从中生成文件对象;然后阅读内容。但是当我将文件的InputStream
发送到'load'方法时,得到一个NullPointerException
这是我的代码:
final class Main
{
protected Properties config;
protected Properties getConfig()
{
if( this.config == null )
{
String filename = this.getClass().getResource("/tiny.properties").getFile();
System.out.print( filename+ "\n" );
File f = new File( filename );
try(InputStream propsFile = new FileInputStream( f ) )
{
int ch = 0;
while( (ch = propsFile.read() ) != -1 )
{
System.out.print((char) ch); // I can get ALL content of File Here
}
this.config.load( propsFile ); // But here I got NullPointerException!
}
catch(IOException exc)
{
assert true : "Can't read properties file!";
}
}
return this.config;
}
}
我的例外是:
Exception in thread "main" java.lang.NullPointerException
at ir.teanlab.japp1.mavenproject1.Main.getConfig(Main.java:43) // this.config.load( ... )
at ir.teanlab.japp1.mavenproject1.Main.getSqlConnection(Main.java:57)
at ir.teanlab.japp1.mavenproject1.Main.<init>(Main.java:67)
at ir.teanlab.japp1.mavenproject1.App.main(App.java:15)
# 1 楼答案
问题是
config
变量尚未初始化,因此仍然为空。因此,在try/catch块中,您应该添加config = new Properties();
另一方面,有一种更简单的方法来获取
InputStream
。我们使用以下技术(Java 6):显然,使用Java7,您可以尝试使用资源
# 2 楼答案
您刚刚在这一行
Properties config;
中创建了一个引用,但尚未创建对象创建一个类似
Properties config=new Properties()
的对象# 3 楼答案
尝试使用remove if条件(if(this.config==null))。 最终代码是:
# 4 楼答案
因为调用
load
方法时config
仍然为空,所以得到了NullPointerException
。您需要像这样初始化config
对象:config = new Properties();
可能最好将其放在空检查的正下方: