当未修复属性文件的路径并通过命令行参数提供时,加载属性文件的最佳方法是什么?
我使用以下代码加载它但是在使用命令行参数运行时它给了我空指针异常:
Properties p = new Properties();
p.load(testClass.class.getResourceAsStream("path to the property file"));
答案 0 :(得分:2)
如果通过命令行获得(完整)路径,则jsut需要提供具有该路径的读取器或输入流。最后,您的代码可能如下所示:
public static void main(String[] args) {
System.out.println("reading property file " + args[0]);
// create new initial properties
Properties properties = new Properties();
// open reader to read the properties file
try (FileReader in = new FileReader(args[0])){
// load the properties from that reader
properties.load(in);
} catch (IOException e) {
// handle the exception
e.printStackTrace();
}
// print out what you just read
Enumeration<?> propertyNames = properties.propertyNames();
while(propertyNames.hasMoreElements()) {
String name = propertyNames.nextElement().toString();
System.out.println(name + ": " + properties.getProperty(name));
}
}