如何在Java args中添加文件路径

问题描述 投票:1回答:3

我正在研究一个项目,我遇到了问题。我需要在cmnd提示符下运行.jar,我需要将.properties文件的路径放入参数中,例如:

java -jar myproject.jar C:\path\to\config.properties

现在我有一个文件静态的路径

FileInputStream in = new FileInputStream("config\\crdb.properties");

我需要以某种方式放置变量而不是静态路径并使用参数更改它。

谢谢。

java command-line jar args
3个回答
1
投票

使用-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);

0
投票

只需使用args数组:

public static void main(String args[]) {
   try (FileInputStream in = new FileInputStream(args[0])) {
     // do stuff..
   }
}

0
投票

如果你正在从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

© www.soinside.com 2019 - 2024. All rights reserved.