Java 运行时.getRuntime().exec(";ls";)没有输出

Java 运行时.getRuntime().exec(";ls";)没有输出,java,Java,ping和date返回了输出,但它没有从“ls”或“pwd”返回任何内容。我最终要做的是运行SSH命令。你知道我下面遗漏了什么吗 //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"); /

ping和date返回了输出,但它没有从“ls”或“pwd”返回任何内容。我最终要做的是运行SSH命令。你知道我下面遗漏了什么吗

//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());


}
我有两个解决办法

第一个解决方案(您需要Java 7):

第二种解决方案:

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

怎么可能呢?在尝试读取它的输入流之前,您要等待进程结束,该输入流现在可能已经关闭。看看我在JUnitforAndroid测试中运行的这个。但这是一个一般的Java问题。您可能希望将
printStackTrace()
替换为
Log
输出。另外-不要忘记还有一个InputStream用于进程的输出到标准错误。它可通过过程API获得。
    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();