java读取环境变量
程序员文章站
2022-03-18 18:07:32
...
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;
class Test
{
// 返回当前系统变量的函数,结果放在一个Properties里边,这里只针对win2k以上的,其它系统可以自己改进
public Properties getEnv() throws Exception
{
Properties prop = new Properties();
String OS = System.getProperty("os.name").toLowerCase();
System.out.println("操作系统:" + OS);
Process p = null;
if (OS.indexOf("windows") > -1)
{
p = Runtime.getRuntime().exec("cmd /c set");
}
if(OS.indexOf("linux") > -1)
{
p = Runtime.getRuntime().exec("sh -c set");
}
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null)
{
int i = line.indexOf("=");
if (i > -1)
{
String key = line.substring(0, i);
String value = line.substring(i + 1);
prop.setProperty(key, value);
}
}
return prop;
}
// 具体用法
public static void main(String[] args)
{
try
{
Test sp = new Test();
Properties p = sp.getEnv();
System.out.println(p.getProperty("PATH")); // 注意大小写,比如读取PATH。Linux下为PATH;Windows为Path
}
catch (Exception e)
{
System.out.println(e);
}
}
}
下一篇: PHP设计模式之装饰器模式定义与用法详解