Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用exec回显多个命令的正确用法_Java_Linux_Runtime_Exec_Runtime.exec - Fatal编程技术网

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

Java 使用exec回显多个命令的正确用法,java,linux,runtime,exec,runtime.exec,Java,Linux,Runtime,Exec,Runtime.exec,在Linux上运行exec与在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 s

在Linux上运行
exec
与在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);
        }
    }
}
另请参见:

不是最佳答案:

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);
        }
    }
}
对解释和更好的答案很感兴趣。另外,如何发送多个命令

见:

有关正确创建和处理流程的许多好提示,请参见。然后忽略它引用
exec
,并使用
ProcessBuilder
创建流程。