在Java中执行某个shell命令,会怎么样?
2个回答
2016-03-13 · 百度知道合伙人官方认证企业
育知同创教育
1【专注:Python+人工智能|Java大数据|HTML5培训】 2【免费提供名师直播课堂、公开课及视频教程】 3【地址:北京市昌平区三旗百汇物美大卖场2层,微信公众号:yuzhitc】
向TA提问
关注
展开全部
Java中执行某个shell命令会执行相应的命令。
java实现执行shell的算法如下:
public void execCommand(String command) throws IOException {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command);
try {
if (proc.waitFor() != 0) {
System.err.println("exit value = " + proc.exitValue());
}
BufferedReader in = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = in.readLine()) != null) {
stringBuffer.append(line+"-");
}
//这里返回执行结果,并打印。
System.out.println(stringBuffer.toString());
} catch (InterruptedException e) {
System.err.println(e);
}
}
比如:echo.sh
内容如下:echo "test java call shell and return value".
那么:
try {
execCommand(../../shell/echo.sh);
} catch (IOException e) {
e.printStackTrace();
}
就会打印出:test java call shell and return value
java实现执行shell的算法如下:
public void execCommand(String command) throws IOException {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command);
try {
if (proc.waitFor() != 0) {
System.err.println("exit value = " + proc.exitValue());
}
BufferedReader in = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = in.readLine()) != null) {
stringBuffer.append(line+"-");
}
//这里返回执行结果,并打印。
System.out.println(stringBuffer.toString());
} catch (InterruptedException e) {
System.err.println(e);
}
}
比如:echo.sh
内容如下:echo "test java call shell and return value".
那么:
try {
execCommand(../../shell/echo.sh);
} catch (IOException e) {
e.printStackTrace();
}
就会打印出:test java call shell and return value
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询