如果存在命令行值,则覆盖属性文件

时间:2013-03-18 03:54:47

标签: java properties command-line-arguments

如果命令行不包含除config.properties文件位置之外的任何参数,我有一个程序将从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"

它应该读取config.properties文件中的所有四个属性。但是假设我正在运行这样的程序 -

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

然后它应该读取参数中的所有属性并覆盖config.properties文件中的属性。

下面是我的代码,在这种情况下工作正常 -

public static void main(String[] args) {

        try {

            readPropertyFiles(args);

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

    private static void readPropertyFiles(String[] args) throws FileNotFoundException, IOException {

        location = args[0];

        prop.load(new FileInputStream(location));

        if(args.length >= 1) {
            noOfThreads = Integer.parseInt(args[1]);
            noOfTasks = Integer.parseInt(args[2]);
            startRange = Integer.parseInt(args[3]);

            tableName = new String[args.length - 4];
            for (int i = 0; i < tableName.length; i++) {
                tableName[i] = args[i + 4];
                tableNames.add(tableName[i]);
            }
        } else {
            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) {

            //Some Other Code

        }
    }   

问题陈述: -

现在我要做的是 - 假设任何人正在运行这样的程序

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

然后在我的程序中,它应该只覆盖noOfThreads -

noOfThreads should be 10 instead of 100

假设那个人正在运行这样的程序 -

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

然后在我的程序中,它应该只覆盖noOfThreadsnoOfTasks -

noOfThreads should be 10 instead of 100
noOfTasks should be 100 instead of 10000

还有其他可能的用例。

有谁能建议我如何实现这种情况?谢谢你的帮助

3 个答案:

答案 0 :(得分:7)

定义命令行输入时如下

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

这意味着必须始终提供noOfThreads来覆盖noOfTasks

要解决此问题,您可以在命令行上将这些指定为系统属性以及文件位置,其他方面也具有默认位置。例如: -

java -jar -Dconfig.file.location="C:\\test\\config.properties" -DNUMBER_OF_THREADS=10 Test.jar

然后

  1. 将文件属性读入Properties
  2. 迭代属性中的键并找到相应的System.getProperty()
  3. 如果找到值,则覆盖属性中的相应条目。
  4. 这样,无论您介绍多少新属性,您的代码都将保持不变。

    您可以更进一步,将所有这些内容封装在PropertyUtil中,同时提供getIntProperty()getStringProperty()等实用程序方法。

    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.Properties;
    
    public class PropertyUtil {
    
      private static final String DEFAULT_CONFIG_FILE_LOCATION = "config.properties";
    
      private String configFileLocation;
    
      private Properties properties;
    
      public PropertyUtil() throws IOException {
    
        this(DEFAULT_CONFIG_FILE_LOCATION);
      }
    
      public PropertyUtil(String configFileLocation) throws IOException {
    
        this.configFileLocation = configFileLocation;
        this.properties = new Properties();
        init();
      }
    
      private void init() throws IOException {
    
        properties.load(new FileInputStream(this.configFileLocation));
    
        for (Object key : this.properties.keySet()) {
    
          String override = System.getProperty((String) key);
    
          if (override != null) {
    
            properties.put(key, override);
          }
        }
      }
    
      public int getIntProperty(String key) {
    
        return this.properties.contains(key) ? Integer.parseInt(properties.get(key)) : null;
      }
    
      public String getStringProperty(String key) {
    
        return (String) this.properties.get(key);
      }
    }
    

    实施例

    config.properties

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

    覆盖NUMBER_OF_THREADS

    java -jar -Dconfig.file.location="C:\\test\\config.properties" -DNUMBER_OF_THREADS=10 Test.jar

    将'NUMBER_OF_THREADS'作为int。

    读取的简短示例
    new PropertyUtil(System.getProperty("config.file.location")).getIntProperty("NUMBER_OF_THREADS");
    

答案 1 :(得分:2)

创建一个循环。

List<String> paramNames = new ArrayList<String>{"NUMBER_OF_THREADS", "NUMBER_OF_TASKS", 
            "ID_START_RANGE", "TABLES"}; // Try to reuse the names from the property file
Map<String, String> paramMap = new HashMap<String, String>();
...
// Validate the length of args here
...
// As you table names can be passed separately. You need to handle that somehow. 
// This implementation would work when number of args will be equal to number of param names
for(int i = 0; i< args.length; i++) {
   paramMap.put(paramNames[i], args[i]); 
}

props.putAll(paramMap);
... // Here props should have it's values overridden with the ones provided

答案 2 :(得分:0)

Properties properties = new Properties();
properties.load(new FileInputStream("C:\\test\\config.properties"));

然后根据您的命令行参数将各个属性设置为:

setProperty("NUMBER_OF_THREADS", args[1]);
setProperty("NUMBER_OF_TASKS", args[2]);

这不会覆盖现有的config.properties文件。