在Java中执行某个shell命令,会怎么样?

2025-04-08 16:38:05
推荐回答(2个)
回答1:

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

回答2:

Java提供了Runtime类来执行shell命令。由于这些是外部的命令,因此异常处理就显得异常重要。将通过一个简单的例子来演示一下。会在shell命令行中打开一个pdf文件。