日期:2014-05-16  浏览次数:20653 次

通过java代码动态设定Linux系统的环境变量
    首先废话几句,原来一直在网易的博客写这种文章,不过越看越觉得还是在JE里比较给力.然后就做了一个非常艰难的决定,以后有需要记录的东西就写在这里.呵呵.
    今天说的是通过java代码动态设定Linux系统的环境变量.老实说我这两天Google了好久也没查到如何做.可能实际用途并不是很大.但是找了半天既然解决了就记录下吧..在这里,感谢下我的同事(师傅)雪饼的帮助.
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class ExecuteCmd {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String[] commonds = {"sh","-c","export JAVA_HOME=/usr/java/jdk;echo $JAVA_HOME"};
		RunSystemCommand(commonds, null);
	}

	public static void RunSystemCommand(String[] command, File file) {
		if (command != null && !command.equals("")) {
			try {
				Process ps = null;
				if (file != null)
					ps = Runtime.getRuntime().exec(command, null, file);
				else
					ps = Runtime.getRuntime().exec(command);
				String message = loadStream(ps.getInputStream());
				String errorMeg = loadStream(ps.getErrorStream());
				System.out.println(message);
				System.out.println("-------");
				System.out.println(errorMeg);
				try {
					ps.waitFor();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private static String loadStream(InputStream in) throws IOException {
		int ptr = 0;
		in = new BufferedInputStream(in);
		StringBuffer buffer = new StringBuffer();
		while ((ptr = in.read()) != -1) {
			buffer.append((char) ptr);
		}
		return new String(buffer.toString().getBytes("ISO-8859-1"), "GBK");
	}
}


其实最主要的一句就是这个
String[] commonds = {"sh","-c","export JAVA_HOME=/usr/java/jdk;echo $JAVA_HOME"};
这个命令的写法.其他的都能Google到.而且据我测试,这些不能写在一起.比如说这样
String tmp_run_cmd = "sh -c 'export JAVA_HOME=/usr/java/jdk;echo $JAVA_HOME'"; //这样是不行的..