在java代码中取出linux中export的变量;读取系统现有的property,添加或覆盖...

下面代码最大的做用是将配置与程序自己分离,这样一样一份jar包能够自由分发到开发,测试,生产环境。

a.在java代码中取出linux中export的变量 java

在linux export一个变量,在java中读取这个变量,并以二进制形式load property文件。 linux

in linux:
export CONFIG_DIR=$HOMEDIR/Properties
in java:

 假设传入的参数fileName是config.properties,下面的代码会将linux脚本中export的变量CONFIG_DIR以 shell

System.getenv(CONFIG_DIR);的方式读取出来,得到配置文件所在的目录,接下来将properties文件以二进制 测试

输入流的方式加载到property中,之后就能够从property得到属性了。 spa

linux中所export的变量会变成java代码运行所在进程的系统变量

public LoadConfiguration(String fileName){
    ConfigurationDir = System.getenv("CONFIG_DIR");
    if ("".equalsIgnoreCase(ConfigurationDir.trim())){
    logger.error("CONFIG_DIR hasn't been set correct!");
    return;
    }
        propertie = new Properties();
        try {
        if (ConfigurationDir.indexOf(ConfigurationDir.length()-1) != '/'){
        ConfigurationDir = ConfigurationDir + "/";
        }
            inputFile = new FileInputStream(ConfigurationDir+fileName);
            propertie.load(inputFile);
            inputFile.close();
        } catch (FileNotFoundException ex){
            System.out.println("Read Properties File --->Failure! Reason: File Path Error or File not exist! Name:" + ConfigurationDir+"/"+fileName);
            ex.printStackTrace();
        } catch (IOException ex){
            System.out.println("Load Configuration File--->Failure! Name:" + ConfigurationDir+"/"+fileName);
            ex.printStackTrace();
        }
    }

b.读取系统现有的property,添加或覆盖配置,而后再设置回去做为系统变量。
Properties p = new Properties(System.getProperties());
    p.put("com.sun.media.jai.disableMediaLib", "true");
    System.setProperties(p);
相关文章
相关标签/搜索