我正在研究一个项目,我遇到了问题。我需要在cmnd提示符下运行.jar,我需要将.properties文件的路径放入参数中,例如:
java -jar myproject.jar C:\path\to\config.properties
现在我有一个文件静态的路径
FileInputStream in = new FileInputStream("config\\crdb.properties");
我需要以某种方式放置变量而不是静态路径并使用参数更改它。
谢谢。
使用-D来放置你的System变量并使用System.getProperty来获取它:
java -Dpath.properties=C:\path\to\config.properties -jar myproject.jar
String pathProp= System.getProperty("path.properties");
FileInputStream in = new FileInputStream(pathProp);
只需使用args
数组:
public static void main(String args[]) {
try (FileInputStream in = new FileInputStream(args[0])) {
// do stuff..
}
}
如果你正在从main方法中读取属性文件,你可以通过args[]
数组访问命令行参数public static void main(String args[])
简单代码如下所示
public static void main(String[] args) {
String splitChar="=";
try {
Map<String, String> propertyList = Files.readAllLines(Paths.get(args[0]))
.stream()
.map(String.class::cast)
.collect(Collectors.toMap(line -> line.split(splitChar)[0],
line -> line.split(splitChar)[1]));
System.out.println(propertyList);
} catch (IOException e) {
e.printStackTrace();
}
}
或者你可以通过vm option
路径
java -Dfile.path = {配置文件的路径} {JavaClassFile执行}
并且您可以获得如下所示的路径(从代码中的任何位置)
System.getProperty("file.path")
和上面的main方法一样,你可以读取属性文件并将其放入我更喜欢的HashMap
中