今天说的是通过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'"; //这样是不行的..
更多通过java代码动态设定Linux系统的环境变量相关文章请关注PHP中文网!