import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main
{
public static void main(String[] args)
{
//得到Java进程的相关Runtime运行对象
Runtime runtime = Runtime.getRuntime();
try
{
//利用exec()方法执行shell 命令 ls -al /root ,并且返回一个Process对象 也就是子进程
//ps:这里都以最简单的shell命令举例。
Process process = runtime.exec("ls -al /root");
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String temp = null;
while ((temp = bufferReader.readLine()) != null)
{
stringBuffer.append(temp);
stringBuffer.append("\n");
}
System.out.println(stringBuffer);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
publicclass {
privatestaticlogger.getLogger(ShellExcuter.class);
/**
linux命令
@param cmd
@param args
*/
runShell(Stringcmd, String[] args) {
in;
br;
out;
bw;
try {
for (String arg : args) {
cmd = cmd +" "+arg;
}
//cmds = new String[] {
//sh",
// "-c",
//cmd };
logger.info(cmd);
ProcessRuntime.getRuntime().exec(cmd);
BufferedReaderbufferReadernew(new(process.getInputStream()));
String temp = null;
while ((temp = bufferReader.readLine()) != null) {
logger.info(temp);
}
BufferedReaderbufferReader2new(new(process.getErrorStream()));
while ((temp = bufferReader.readLine()) != null) {
logger.info(temp);
}
.close();
.close();
.waitFor();
.destroy();
catch (Throwable e) {
logger.error("执行linux命令出错:"e.getMessage());
e.printStackTrace();
}
}
}
java调用shell死锁 java调用shell获取返回值
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章