代码如下:
1 public static Map getEnv() {
2 Map map = new HashMap();
3 String OS = System.getProperty("os.name").toLowerCase();
4
5 Process p = null;
6
7 /**
8 * 以windows为例.
9 */
10 if(OS.indexOf("windows") > -1) {
11 try {
12 p = Runtime.getRuntime().exec("cmd /c set");
13 BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
14
15 String line;
16
17 while((line = br.readLine()) != null) {
18 String[] str = line.split("=");
19 map.put(str[0], str[1]);
20 }
21 } catch(IOException ioe) {
22 ioe.printStackTrace();
23 }
24 }
25 return map;
26 }
上述代码将windows系统中的环境变量转换为java的Map,只要通过map.get(key)就能得到环境变量值,比如map.get("JAVA_HOME"),得到JAVA_HOME的值,即JAVA_HOME的系统路径。
值得注意的是在java中使用windows操作系统命令时要在命令前加
cmd /c,否则java会报错(),错误列表如下:
1 java.io.IOException: CreateProcess: ${执行的操作命令表达式或者.bat文件} error=2
2 at java.lang.Win32Process.create(Native Method)
3 at java.lang.Win32Process.<init>(Win32Process.java:63)
4 at java.lang.Runtime.execInternal(Native Method)
5 at java.lang.Runtime.exec(Runtime.java:566)
6 at java.lang.Runtime.exec(Runtime.java:428)
7 at java.lang.Runtime.exec(Runtime.java:364)
8 at java.lang.Runtime.exec(Runtime.java:326)
9 at org.apache.jsp.ChangeDirBajaRCXX_jsp._jspService(ChangeDirBaja
10 p.java:185)
该错误的解释:
The error 2 comes from the CreateProcess() call, from MSDN (GetLastError():
2 - The system cannot find the file specified. - ERROR_FILE_NOT_FOUND
So, it means the path you passed cannot be found. Maybe you did not configure your Runtime class correctly.
put the batch file in the same directory as the class file and use (for a test):
posted on 2006-07-03 17:11
想飞的鱼 阅读(5869)
评论(2) 编辑 收藏 所属分类:
java