如何在Java参数中向文件添加路径

如何在Java参数中向文件添加路径,java,command-line,jar,args,Java,Command Line,Jar,Args,我正在做一个项目,我来解决这个问题。 我需要在cmnd提示符上运行.jar,并且需要将.properties文件的路径放入参数中,例如: java -jar myproject.jar C:\path\to\config.properties 现在我有了一个路径来归档satatic FileInputStream in = new FileInputStream("config\\crdb.properties"); 我需要以某种方式放置变量而不是静态路径,并用参数更改它 谢谢。只需使用ar

我正在做一个项目,我来解决这个问题。 我需要在cmnd提示符上运行.jar,并且需要将.properties文件的路径放入参数中,例如:

java -jar myproject.jar C:\path\to\config.properties
现在我有了一个路径来归档satatic

FileInputStream in = new FileInputStream("config\\crdb.properties");
我需要以某种方式放置变量而不是静态路径,并用参数更改它


谢谢。

只需使用
args
数组:

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

使用-D放置系统变量,并使用System.getProperty获取该变量:

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


如果您正在从main方法读取属性文件,则只需通过
args[]
array
publicstaticvoidmain(stringargs[])访问命令行参数即可。
下面这样的简单代码也可以

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();
    }
}

与上面的main方法相同,您可以读取属性文件并将其放入
HashMap
,我更喜欢它

,这就是主函数中的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();
    }
}
System.getProperty("file.path")