我已经坚持了将近一个小时,所以请帮助我。
我使用netbeans并在我的Sources Packages
下面有一个名为com.cmsv1.properties
的软件包。在这个包中,我有1个java类和.properties
文件。被称为config.java
和config.properties
。
我尝试过从互联网上获得的许多解决方案,但没有任何效果。我总是得到nullPointerException
。
以下是我尝试过的解决方案:
try
{
Properties prop = new Properties();
InputStream is = config.class.getResourceAsStream("config.properties");
}
catch (Exception e)
{
System.out.println("got error");
}
另一个是:
try
{
Properties prop = new Properties();
InputStream input = config.class.getClassLoader().getResourceAsStream("config.properties");
prop.load(input);
}
catch (Exception e)
{
System.out.println("got error");
}
还有几个解决方案。请告诉我怎么做这个。请记住,我的java类和.properties文件都在同一个包中。提前谢谢。
答案 0 :(得分:0)
如果你的编译器正在将你的属性文件编译到你的jar中,那么这应该有效:
this.getClass().getResourceAsStream("config.properties");
答案 1 :(得分:0)
你的第一次尝试几乎完全正确:
try
{
Properties prop = new Properties();
InputStream is = config.class.getResourceAsStream("config.properties");
}
catch (Exception e)
{
System.out.println("got error");
}
除非您需要加载和关闭InputStream:
Properties prop = new Properties();
try (InputStream is = config.class.getResourceAsStream("config.properties")) {
prop.load(is);
}
此外,您需要捕获仅您需要捕获的异常:
catch (IOException e)
这是因为其他异常,尤其是未经检查的异常(如NullPointerException),表示程序员错误。你没有抓住这些,你让他们让你的程序失败,所以你可以发现并修复它们。隐藏它们并不能使你的程序正常工作!
始终显示捕获的异常的堆栈跟踪,使用日志记录语句,异常链接或printStackTrace()
。如果出现问题,你想知道它为什么会发生以及它发生在哪里:
catch (IOException e)
{
e.printStackTrace();
}
关于Class.getResource与ClassLoader.getResource的使用,应始终使用Class.getResource(或Class.getResourceAsStream)。其中的原因是它可以在Java 9模块化应用程序中使用。
如果getResourceAsStream返回null,那是因为您的属性文件与编译的.class文件不在同一位置。
答案 2 :(得分:-2)
(没有足够的评论声誉)
你试过这个吗?
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertiesFile);
properties.load(input);
答案 3 :(得分:-2)
public Properties getPropertiesFromFile(String propertieFileName) throws IOException
{
try (InputStream propertyFile = this.getClass().getClassLoader().getResourceAsStream(propertieFileName)
{
if (propertyFile == null)
{
//logger not found
}
Properties propeties = new Properties();
propeties.load(propertyFile);
return propeties;
}
}