importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;publicclassExecuteShellCommand{publicstaticvoidmain(String[]args){Stringcommand="dir";// 执行dir命令try{// 创建Runtime对象Runtimeruntime=Runtime.getRuntime();// 执行命令Processprocess=runtime.exec(command);// 获...
}catch(TimeoutException ex) {StringerrorMessage="The command ["+ command +"] timed out."; logger.error(errorMessage, ex);returnnewExecuteResult(-1,null); }catch(ExecutionException ex) {StringerrorMessage="The command ["+ command +"] did not complete due to an execution error."; logger....
3. 完整代码示例 下面是完整的Java代码示例: importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;publicclassJavaExecuteShellCommand{publicstaticvoidmain(String[]args){try{// 创建ProcessBuilder对象ProcessBuilderprocessBuilder=newProcessBuilder();// 设置...
run.exec(cmd)调用的是RunTime下的方法,代码如下 publicProcess exec(String command)throwsIOException {returnexec(command,null,null); } 进而调用(我们只需看最后一行) publicProcess exec(String command, String[] envp, File dir)throwsIOException {if(command.length() == 0)thrownewIllegalArgumentException(...
public class Test { public static void main(String[] args) throws Exception { try { //execute shell command: df -k . Process fileSystemDfInfo = Runtime.getRuntime().exec("df -k ...
*/publicintexec(Stringcmds)throwsException{InputStreamstdOut=null;InputStreamstdErr=null;StringoutStr="";StringoutErr="";intret=-1;try{if(login()){// Open a new {@link Session} on this connectionSessionsession=conn.openSession();// Execute a command on the remote machine.session.execCommand...
* 执行shell命令 * @param command * @return */ public int execute(final String command) { int returnCode = 0; JSch jsch = new JSch(); MyUserInfo userInfo = new MyUserInfo(); try { //创建session并且打开连接,因为创建session之后要主动打开连接 ...
Java可以使用Runtime和ProcessBuilder两种方式执行Shell命令。...一、使用Runtime执行Shell命令 Java的Runtime类提供了一个可以执行系统命令的方法,exec()方法可以执行任何系统命令,例子如下: try { Process process...二、使用Proce...
Java可以使用Runtime和ProcessBuilder两种方式执行Shell命令。...一、使用Runtime执行Shell命令 Java的Runtime类提供了一个可以执行系统命令的方法,exec()方法可以执行任何系统命令,例子如下: try { Process process...二、使用Proce...
Shell Command Execution Library This is a Java library that intends to make it easier and safer to execute shell commands on the operating system using Runtime.exec(). Note: It is probably advised to just use java's ProcessBuilder but this is a fun project to work on. ...