繁体   English   中英

如果在命令行参数中指定,则覆盖属性文件值

[英]Overwrite property file values if specified in the command line arguments

我正在一个项目中,我需要从config.properties文件中读取所有内容。 以下是我的config.properties文件-

NUMBER_OF_THREADS: 100
NUMBER_OF_TASKS: 10000
ID_START_RANGE: 1
TABLES: TABLE1,TABLE2

我正在像这样从命令提示符运行我的程序-并且工作正常。

java -jar Test.jar "C:\\\\test\\\\config.properties"

以下是我的程序-

private static Properties prop = new Properties();

private static int noOfThreads;
private static int noOfTasks;
private static int startRange;
private static String location;
private static List<String> tableNames = new ArrayList<String>();

public static void main(String[] args) {

        location = args[0];

        try {

            readPropertyFiles();

        } catch (Exception e) {
            LOG.error("Threw a Exception in" + CNAME + e);
        }
    }

    private static void readPropertyFiles() throws FileNotFoundException, IOException {

        prop.load(new FileInputStream(location));

        noOfThreads = Integer.parseInt(prop.getProperty("NUMBER_OF_THREADS").trim());
        noOfTasks = Integer.parseInt(prop.getProperty("NUMBER_OF_TASKS").trim());
        startRange = Integer.parseInt(prop.getProperty("ID_START_RANGE").trim());
        tableNames = Arrays.asList(prop.getProperty("TABLES").trim().split(","));


        for (String arg : tableNames) {

            //Other Code
        }
    }

问题陈述:-

现在,我想做的是-从命令提示符处假设我要传递其他参数,例如NUMBER_OF_THREADS, NUMBER_OF_TASKS, ID_START_RANGE, TABLES以及config.properties file ,那么它应该覆盖config.properties file的值。 因此,如果我像这样运行程序,

java -jar Test.jar "C:\\\\test\\\\config.properties" t:10 n:100 i:2 TABLES:TABLE1 TABLES:TABLE2 TABLES:TABLE3

然后在我的程序中

noOfThreads should be 10 instead of 100
noOfTasks should be 100 instead of 10000
startRange should be 2 instead of 1
tableNames should have three table TABLE1, TABLE2, TABLE3 instead of TABLE1 and TABLE2.

如果需要覆盖config.property文件,将遵循上述格式。

但是如果我这样跑-

java -jar Test.jar "C:\\\\test\\\\config.properties"

然后它应该从config.properties file读取所有内容。

通常,如果我要在命令行中传递参数以及config.property文件位置,则我想覆盖config.properties file

谁能给我一个做这种情况的例子(干净的方式)?

您可以手动合并它们,但是需要在命令行选项上使用上下文,如何知道应该将TABLE3添加到tableNames数组中,而不是10、100和2?

如果您要像这样更改命令行:

java -jar Test.jar "C:\\test\\config.properties" 10 100 2 TABLES:TABLE1 TABLES:TABLE2 TABLES:TABLE3

然后,您可以在读取属性文件并插入或添加属性条目之后,在main方法中循环浏览命令行参数。

暂无
暂无

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

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