简体   繁体   English

使用命令行参数加载属性文件-Java

[英]Load property file with command line arguments - Java

What is the best way to load a property file when path to the property file is not fixed and provided via command line arguments? 当属性文件的路径未固定并通过命令行参数提供时,加载属性文件的最佳方法是什么?

I am using the following code to load it but it is giving me null pointer exception when run using command line arguments: 我正在使用以下代码来加载它,但是使用命令行参数运行时,它给了我空指针异常:

Properties p = new Properties();        
p.load(testClass.class.getResourceAsStream("path to the property file"));

If you get the (full) path via command line, you jsut need to provide a reader or input stream with that path. 如果通过命令行获得(完整)路径,则需要为阅读器或输入流提供该路径。 In the end, your code could look like this: 最后,您的代码可能如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM