今天說的是透過java程式碼動態設定Linux系統的環境變數.老實說我這兩天Google了好久也沒查到如何做.可能實際用途並不是很大.但是找了半天既然解決了就記錄下吧
Java程式碼
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'" ; //這樣是不行的..