使用命令行参数加载属性文件-Java
当属性文件的路径不是固定的并且不是通过命令行参数提供时,加载属性文件的最佳方法是什么 我正在使用以下代码加载它,但在使用命令行参数运行时,它给了我空指针异常:使用命令行参数加载属性文件-Java,java,properties,Java,Properties,当属性文件的路径不是固定的并且不是通过命令行参数提供时,加载属性文件的最佳方法是什么 我正在使用以下代码加载它,但在使用命令行参数运行时,它给了我空指针异常: Properties p = new Properties(); p.load(testClass.class.getResourceAsStream("path to the property file")); 如果通过命令行获得(完整)路径,则需要提供具有该路径的读取器或输入流。最后,您的代码可能如下所示:
Properties p = new Properties();
p.load(testClass.class.getResourceAsStream("path to the property file"));
如果通过命令行获得(完整)路径,则需要提供具有该路径的读取器或输入流。最后,您的代码可能如下所示:
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));
}
}
publicstaticvoidmain(字符串[]args){
System.out.println(“读取属性文件”+args[0]);
//创建新的初始属性
属性=新属性();
//打开reader以读取属性文件
try(FileReader in=newfilereader(args[0])){
//从该读取器加载属性
属性。荷载(in);
}捕获(IOE异常){
//处理异常
e、 printStackTrace();
}
//把你刚读到的东西打印出来
枚举propertyNames=properties.propertyNames();
while(propertyNames.hasMoreElements()){
字符串名称=propertyNames.nextElement().toString();
System.out.println(name+”:“+properties.getProperty(name));
}
}
好吧,我假设属性文件的路径不是有效路径。为什么有人会在打包的代码中为路径提供命令行参数——这太奇怪了。Post an-这是胡说八道。因为同一个jar将在不同的环境中执行,因此路径可能会更改。并且正确地提供了路径,因为通过提供参数,从eclipse运行时,该路径工作正常;但这不是MVCE。