今天说的是通过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中文网!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号