初学Java .目的是读取配置文件,但是总是报错“静态变量非最终值”之类的错误?
- Java code
public class dbUnit { private static Properties dbConfig; static { try { InputStream dbPropertiesIO = dbUnit.class.getResourceAsStream("/dbConfig.properties"); dbConfig.load(dbPropertiesIO); dbPropertiesIO.close(); } catch (Exception e) { throw new ExceptionInInitializerError(e); } } public static String getPop() { return dbConfig.getProperty("server"); }}
求解?
------解决方案--------------------------------------------------------
最基本的问题, 你只初始化Properties的引用,但是没关联Properties对象,所以会出现空指针异常,
private static Properties dbConfig= new Properties();
下面可以了, 最开始看你这程序的时候我也很困惑,因为我不只一次写过这东西,但是一直没注意你成员变量,
下次注意吧。
------解决方案--------------------------------------------------------
首先 确定你的 properties 是否是与你当前文件是否是一个文件夹,如果是 我这样写 你那段获取输出流的代码
InInputStream dbPropertiesIO = Test4.class.getClassLoader(). getResourceAsStream( "dbConfig1.properties");
// 获取指定类 Test4 当前包下对应的 dbConfig1.properties 文件
如果不是 你获取输出流时,我建议你先获取文件 并且用 file.exits看看 你的文件路径是否有问题,如果不正确最少要获取到文件对象再获取文件流啊。