1

I'm trying to execute unix commands in java, like system("ls"); in C. I tried this but it doesn't print anithing:

Process p=Runtime.getRuntime().exec("ls");
OutputStream in=p.getOutputStream();
PrintStream print = new PrintStream(in);
print.println("String");

Any ideas?

3 Answers3

0

You can use the newer ProcessBuilder class, which has more options than the Runtime.exec method. The reason why you don't see any output is because the standard output stream of the new process is by default connected to the JVM via a pipe. You can make the new process inherit the JVM's standard output using the redirectOutput method:

ProcessBuilder pb = new ProcessBuilder("ls");
pb.redirectOutput(Redirect.INHERIT);
Process p = pb.start();

You can get a similar result using a shell redirection to the controlling terminal:

ProcessBuilder pb = new ProcessBuilder("sh", "-c", "ls > /dev/tty");
Process p = pb.start();
Joni
  • 108,737
  • 14
  • 143
  • 193
  • I get the "Redirect cannot be resolved to a variable" error in Redirect.INHERIT, I have to import something? eclipse doesn't suggest anything –  Dec 31 '13 at 12:48
  • You can add `import java.lang.ProcessBuilder.Redirect` or write `ProcessBuilder.Redirect` instead of just `Redirect` – Joni Dec 31 '13 at 12:49
  • I find ProcessBuilder but not ProcessBuilder.Redirect, "cannot be resolved" again :S –  Dec 31 '13 at 12:57
  • 1
    In that case you must be using Java 6 or an earlier version; ProcessBuilder.Redirect was added in Java 7. There are workarounds like using a shell redirection (see my update) or reading the pipe yourself (like in Serdar's answer). Considering that Java 6 has already reached end of public updates and even the end of premier support from Oracle you may want to consider migrating to Java 7 or 8. – Joni Dec 31 '13 at 13:10
0

There is nice library for doing this zt-exec

new ProcessExecutor().command("ls")
      .redirectOutputAsInfo().execute();

or

String output = new ProcessExecutor().command("ls")
      .readOutput(true).execute()
      .outputUTF8(); 
MariuszS
  • 30,646
  • 12
  • 114
  • 155
0

You must read command response (if any) from Process input stream as follows:

        Process p=Runtime.getRuntime().exec("net time");

        InputStream is = p.getInputStream(); //or p.getErrorStream() on error
        int c;
        StringBuilder commandResponse = new StringBuilder();

        while( (c = is.read()) != -1) {    //read until end of stream
            commandResponse.append((char)c);
        }
        System.out.println(commandResponse);   //Print command response
        is.close();

But if an error occurs Process writes to error stream so you have to check both streams.

Serdar
  • 383
  • 1
  • 9