java调用shell命令,怎么通过java去调用并执行shell脚本以及问题总结

1,怎么通过java去调用并执行shell脚本以及问题总结// 用法:Runtime.getRuntime().exec("命令");String shpath="/test/test.sh";//程序路径Process process =null;String command1 = “chmod 777 ” + shpath;tryRuntime.getRuntime().exec(command1 ).waitFor();} catch (IOException e1)e1.printStackTrace();}catch (InterruptedException e)e.printStackTrace();}String var="201102";/参数String command2 = “/bin/sh ” + shpath + ” ” + var;Runtime.getRuntime().exec(command2).waitFor();
2,java 调用 shell 脚本在写程序时,有时需要在java程序中调用shell脚本 , 可以通过Runtime的exec方法来调用shell程序,运行脚本 。每个Java 应用程序都有一个Runtime 类实例,使应用程序能够与其运行的环境相连接 。通过Runtime对象可以返回运行环境的情况 , 包括CPU数,虚拟机内存大小等,并能够通过exec方法调用执行命令 。可以通过getRuntime 方法获取当前Runtime实例 。public boolean ExeShell(){ Runtime rt = Runtime.getRuntime(); try { Process p = rt.exec(checkShellName); if(p.waitFor() != 0) return false; } catch (IOException e) { SysLog.error("没有找到检测脚本"); return false; } catch (InterruptedException e) { e.printStackTrace(); return false; } return true; } 其中p.waitFor()语句用来等待子进程结束,其返回值为进程结束退出码 。
3,java怎么调用shell脚本String cmdstring = "chmod a+x test.sh"; Process proc = Runtime.getRuntime().exec(cmdstring); proc.waitFor(); //阻塞 , 直到上述命令执行完 cmdstring = "bash test.sh"; //这里也可以是ksh等 proc = Runtime.getRuntime().exec(cmdstring); // 注意下面的操作 string ls_1; BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(proc.getInputStream()); while ( (ls_1=bufferedReader.readLine()) != null); bufferedReader.close(); proc.waitFor();为什么要有上面那段操作呢?原因是:可执行程序的输出可能会比较多,而运行窗口的输出缓冲区有限,会造成waitFor一直阻塞 。解决的办法是,利用Java提供的Process类提供的getInputStream,getErrorStream方法让Java虚拟机截获被调用程序的标准输出、错误输出,在waitfor()命令之前读掉输出缓冲区中的内容 。在写程序时,有时需要在java程序中调用shell脚本,可以通过runtime的exec方法来调用shell程序,运行脚本 。每个java 应用程序都有一个runtime 类实例,使应用程序能够与其运行的环境相连接 。通过runtime对象可以返回运行环境的情况,包括cpu数,虚拟机内存大小等,并能够通过exec方法调用执行命令 。可以通过getruntime 方法获取当前runtime实例 。public boolean exeshell()其中p.waitfor()语句用来等待子进程结束,其返回值为进程结束退出码 。【java调用shell命令,怎么通过java去调用并执行shell脚本以及问题总结】

    推荐阅读