学无止境  
日历
<2005年9月>
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678
统计
  • 随笔 - 9
  • 文章 - 0
  • 评论 - 2
  • 引用 - 0

导航

常用链接

留言簿(2)

随笔分类

随笔档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜

 
In JDK 1.4 System.getenv() is deprecated. (In JDK 1.5 it is un-deprected again.) The getProperty method is now the correspoding method to get the variables. For example: System.getProperty("java.class.path",""). But it doesn't work for user defined environment variable. This problem can be solved by using the following code:
import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
* Environment class simulates the System.getenv() method which is deprecated
* on java 1.4.2
*
* @author v-josp
*
*/
public class TestRoot
{
//result of all enviornment variables
private static BufferedReader commandResult;

static
{
String cmd = null;
String os = null;

//getting the OS name
os = System.getProperty("os.name").toLowerCase();

// according to OS set the command to execute
if(os.startsWith("windows"))
{
cmd = "cmd /c SET";
}
else
{
cmd="env";
}

try
{
//execute the command and get the result in the form of InputStream
Process p = Runtime.getRuntime().exec(cmd);

//parse the InputStream data
InputStreamReader isr = new InputStreamReader(p.getInputStream());
commandResult= new BufferedReader(isr);
}
catch (Exception e)
{
System.out.println("OSEnvironment.class error: " + cmd + ":" + e);
}
}

/**
* This method is used to get the path of the given enviornment variable. This
* method tries to simulates the System.getenv() which is deprecated on java 1.4.2
*
* @param String - name of the environment variable
* @param String - default value
* @return
*/
public static String getenv(String envName,String defaultValue)
{
String line = null;
try
{
while ((line = commandResult.readLine()) != null)
{
if(line.indexOf(envName)>-1)
{
return line.substring(line.indexOf(envName)+envName.length()+1);
}
}
return defaultValue;
}
catch (Exception e)
{
return defaultValue;
}
}

public static void main(String args[])
{
System.out.println(TestRoot.getenv("CLASSPATH",""));
}
}

Output
_____
F:\software\javaws-1_2-dev\jnlp.jar;
posted on 2005-09-14 02:36 lucia 阅读(645) 评论(0)  编辑  收藏 所属分类: JAVA

只有注册用户登录后才能发表评论。


网站导航:
 
 
Copyright © lucia Powered by: 博客园 模板提供:沪江博客