0

Perhaps there are significant differences between running exec on Linux versus Windows, beyond the obvious, so I grabbed a demo, but it also crashes when sent a cmdarray of "hello world".

What is the correct usage for a "command array" of "echo" commands?

crash:

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)

adapted code:

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);
        }
    }
}

see also: sending a cmdarray for exec to process -- hello world

Community
  • 1
  • 1
Thufir
  • 8,216
  • 28
  • 125
  • 273
  • 1
    See also [When Runtime.exec() won't](http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html) for many good tips on creating and handling a process correctly. Then ignore it refers to `exec` and use a `ProcessBuilder` to create the process. – Andrew Thompson Apr 07 '16 at 01:47

1 Answers1

0

Not the best answer:

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);
        }
    }
}

Definitely interested in an explanation and better answer. Also, how do you send multiple commands???

see:

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

Community
  • 1
  • 1
Thufir
  • 8,216
  • 28
  • 125
  • 273