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

风格不统一 提交于 2019-11-30 01:58:07

下面代码最大的作用是将配置与程序本身分离,这样同样一份jar包可以自由分发到开发,测试,生产环境。

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

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

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

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

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

输入流的方式加载到property中,以后就可以从property获得属性了。

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!