1

ping and date returned output, but it's not returning anything from "ls" or "pwd". What I want to do ultimately is run an SSH command. Any idea what I am missing below?

//Works and shows the output
executeCommand("ping -c 3 " + "google.com");

//Works and shows the output
executeCommand("date");

//Does not work. No output
executeCommand("sudo ls");

//Does not work. No output
executeCommand("ls");


private void executeCommand(String command) {

 StringBuffer output = new StringBuffer();

 Process p;
  try {
    p = Runtime.getRuntime().exec(command);
    p.waitFor();
    BufferedReader reader = 
    new BufferedReader(new InputStreamReader(p.getInputStream()));

    String line = "";           
    while ((line = reader.readLine())!= null) {
       output.append(line + "\n");
    }

 } catch (Exception e) {
    e.printStackTrace();
}

    Log.d("Output", "Output: " + output.toString());


}
Wakaran
  • 91
  • 1
  • 11
  • 1
    How can it? You're waiting until the process ends before trying to read it's input stream, which is probably closed by now. Take a look at [this example](https://stackoverflow.com/questions/15218892/running-a-java-program-from-another-java-program/15220419#15220419) – MadProgrammer Jan 10 '14 at 02:14
  • I'm running this in Junit for android test. But this is a general Java question. – Wakaran Jan 10 '14 at 02:14
  • You might want to replace the `printStackTrace()` with a `Log` output. – ug_ Jan 10 '14 at 02:21
  • Also - don't forget there is also an InputStream for the process' output to standard error. It's available in the Process API via [getErrorStream()](http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#getErrorStream()). – Scott Heaberlin Jan 10 '14 at 02:42

1 Answers1

0

I have two solutions

first solution (you need Java 7):

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

second solution:

    Process p=Runtime.getRuntime().exec("ls");

    InputStream is = p.getInputStream();
    int c;
    StringBuilder commandResponse = new StringBuilder();

    while( (c = is.read()) != -1) {
        commandResponse.append((char)c);
    }
    System.out.println(commandResponse);
    is.close();