使用exec回显多个命令的正确用法

时间:2016-04-06 09:30:41

标签: java linux runtime exec runtime.exec

在Linux和Windows上运行exec之间可能存在显着差异,超出了明显的范围,因此我抓住了一个演示,但在发送cmdarray“hello world”时它也会崩溃。

“echo”命令的“命令数组”的正确用法是什么?

碰撞:

run:
echo hello world...?  cannot open notepad
java.io.IOException: Cannot run program "echo hello world 1": error=2, No such file or directory
BUILD SUCCESSFUL (total time: 0 seconds)

改编代码:

package com.tutorialspoint;

public class RuntimeDemo {

    public static void main(String[] args) {
        try {
            // create a new array of 2 strings
            String[] cmdArray = new String[2];

            // first argument is the program we want to open
            cmdArray[0] = "echo hello world 1";

            // second argument is a txt file we want to open with notepad
            cmdArray[1] = "echo hello world 2";

            // print a message
            System.out.println("echo hello world...?  cannot open notepad");

            // create a process and execute cmdArray
            Process process = Runtime.getRuntime().exec(cmdArray);

            // print another message
            System.out.println("example.txt should now open.");

        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
}

另见:sending a cmdarray for exec to process -- hello world

1 个答案:

答案 0 :(得分:0)

不是最好的答案:

package com.tutorialspoint;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import static java.lang.System.out;

public class RuntimeDemo {

    public static void main(String[] args) throws InterruptedException, IOException {
        String[] cmd = {"echo", "hello world"};
        Process process = Runtime.getRuntime().exec(cmd);
        BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;
        while ((line = input.readLine()) != null) {
            out.println(line);
        }
    }
}

绝对对解释和更好的答案感兴趣。另外,你如何发送多个命令???

请参阅:

https://stackoverflow.com/a/3032498/262852