What we are talking about today is to dynamically set environment variables of the Linux system through java code. To be honest, I have been searching on Google for a long time in the past two days and have not been able to find out how to do it. Maybe it is not very useful in practice. But after searching for a long time, I will record it now that I have solved it. Come on
Java code
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"); } }
In fact, the most important sentence is this
String[] commonds = {"sh","-c","export JAVA_HOME=/usr/java/jdk;echo $JAVA_HOME"};
How to write this command. Others can be found on Google. And according to my test, these cannot be written together. For example,
String tmp_run_cmd = "sh -c 'export JAVA_HOME=/usr/java/jdk;echo $JAVA_HOME'" ; //This is not possible..
For more related articles about dynamically setting environment variables of the Linux system through java code, please pay attention to the PHP Chinese website!