【问题标题】:correct usage to echo multiple commands with exec使用 exec 回显多个命令的正确用法
【发布时间】:2016-04-06 09:30:41
【问题描述】:

在 Linux 和 Windows 上运行 exec 与在 Windows 上运行之间可能存在明显差异,所以我抓了一个演示,但在发送 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

【问题讨论】:

  • 另请参阅When Runtime.exec() won't,了解有关正确创建和处理流程的许多好技巧。然后忽略它引用exec并使用ProcessBuilder创建进程。

标签: java linux runtime exec runtime.exec


【解决方案1】:

不是最佳答案:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 2014-03-07
    • 1970-01-01
    • 2015-05-27
    相关资源
    最近更新 更多