从Java执行多个命令行的方法

3

我正在寻找一种从Java中执行多个shell命令的方法。我在stackoverflow上找到了这个方法,但它只能用于每个会话执行一个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();  
    }  

有没有一种方法使用上面的代码在同一个会话中执行多个命令?
4个回答

0

你可以轻松地在一个 for 循环 中编写这段代码。


0
也许你可以将这些命令分组到一个 shell 脚本中,然后只执行该脚本。

0
您可以编写一个可执行的 shell 脚本或批处理文件,其中包含一堆命令,并将其作为一个命令执行。

0
首先,这不是你使用 Runtime.exec() 的方式:第一个参数是 可执行文件,其他参数是该可执行文件的参数。
现在,你的代码正在尝试执行一个名为"ls -la"的文件,当然这个文件不存在。
将你的代码更改为以下内容:
String[] command = {"ls", "-la"}; // Use an array
Runtime.getRuntime().exec(command);  

谢谢您的回复,有没有办法用几个命令的 shell 调用来完成它? - Mas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接