2012-07-12 184 views
2

我正在寻找从java执行几个comman shell的方式。我发现这在计算器,但它不仅有利于执行每个会话一个命令shell:从java执行多个命令shell

try { 
     // Execute command 
     String command = "ls -la"; 
     StringBuffer ret=new StringBuffer(); 
     Process p = Runtime.getRuntime().exec(command); 

     // Get the input stream and read from it 
     InputStream in = child.getInputStream(); 
     int c; 
     while ((c = in.read()) != -1) { 
     ret.append((char)c); 
     } 
     in.close(); 
     System.out.println(ret.toString()); 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } 

反正是有使用上面的代码相同的会话执行多个命令?

+0

你说的是哪届? – adranale 2012-07-12 12:22:41

回答

0

您可以在for-loop内轻松编写此代码。

0

也许你可以将这些命令分组到shell脚本中,然后执行它。

0

您可以用一堆命令编写可执行的shell脚本或bat文件,并将其作为一个命令执行。

0

首先,这不是你如何使用Runtime.exec():第一个参数是可执行文件,其他参数是该可执行文件的参数。

现在,您的代码正试图执行一个名为字面意思为"ls -la"的文件,这当然不存在。

你的代码改成这样:

String[] command = {"ls", "-la"}; // Use an array 
Runtime.getRuntime().exec(command); 
+0

感谢您的回应,是否有几个命令shell调用它呢? – Mas 2012-07-12 12:34:14