加载属性文件的Java NullPointerException

public class SupplierCalculatorApplet extends JApplet{ ... public void init(){ loadProperties(); ... } ... private void loadProperties() { language = "en-us";//getParameter("Language"); prop = new Properties(); try { URL urlToProps = this.getClass().getResource("config/" + language + ".properties"); prop.load(urlToProps.openStream());//Exception Caught Here } catch (IOException e) { } } 

在上面指出的行中可以找到例外情况。 无论语言是否是有效的属性文件,我都会在同一行上捕获相同的exception。

你没有给我们很多工作,但我的猜测是urlToPropsnull ,因为如果没有找到资源, Class#getResource返回null ,但你没有在图片代码中进行防御性检查。 所以urlToProps.openStream()部分会抛出一个NPE。

改成:

 prop.load(this.getClass().getResourceAsStream("/config/" + language + ".properties"));