Java获取本地环境变量

获取本地环境变量是项目开发中常用的一个操作,写了段小代码,免得哪天忘记了。

package com.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class GetEnvVar {
    private BufferedReader getAllEnvVars() {
        BufferedReader variables = null;
        String command = null;
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.startsWith("windows")) {
            command = "cmd /c SET";
        } else {
            command = "env";
        }
        try {
            Process process = Runtime.getRuntime().exec(command);
            InputStreamReader reader = new InputStreamReader(process.getInputStream());
            variables = new BufferedReader(reader);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        return variables;
    }
      
    private String getByVarName(String name) {
        BufferedReader variables = getAllEnvVars();
        String line = null;
        try {
            line = variables.readLine();
            String key = null;
            while (line != null) {
                int equalSign = line.indexOf('=');
                key = line.substring(0, equalSign);
                if (name.equalsIgnoreCase(key)) {
                    return line.substring(equalSign + 1);
                }
                line = variables.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        return null;
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        GetEnvVar worker = new GetEnvVar();
        System.out.println(worker.getByVarName(args[0]));
    }
}


你可能感兴趣的:(java,环境变量)