无法从runtime.getruntime.exec()运行/获取输出(android java)

时间:2015-07-13 03:14:26

标签: java android

我有一个php可执行的原生二进制文件来自游戏市场中的一些php服务器应用程序,我在平板电脑上使用shell应用程序尝试过它们。

我正在创建一个新应用并尝试运行它并接收输出但它无法正常工作。

我的功能是将资产复制到设备。我也有一些代码来测试它们是否正确

File file4 = new File(getFilesDir().getAbsolutePath()+"/php");
file4.setExecutable(true);
s+=file4.getName();
s+=file4.exists();
s+=file4.canExecute();
s+=file4.length();

它确实说存在正确的文件名,可执行且文件长度正确。

现在,我尝试运行它并没有给我php输出。

我已尝试php -v版本输出,但无法正常工作。

我已尝试过php phpfile.php >> file.html并阅读该文件,但无法正常使用。

我已尝试使用-f并且没有使用-f,但它无法正常工作。

最后,我尝试将参数和dir单独分配给.exec,但仍然没有给出正确的输出

当我使用runtime.getruntime.exec等其他命令尝试/bin/cmd/ls时,它会提供正确的输出。

php二进制文件可以正常工作,我已经在我的设备上尝试了其中两个,但是我的应用程序都无法正常工作。

我很感激帮助。

s+=runphp();

public String runphp(){
try {
    String prog=  "./php";
    String[] env= { "-f", getFilesDir().getAbsolutePath()+"/phprun.php"}; // ">>","phpoutput.txt"
    File dir=  new File(getFilesDir().getAbsolutePath());
    Process p = Runtime.getRuntime().exec(prog,env,dir);

    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
     String line=null;
     String output="";
     while ((line = in.readLine()) != null) {
        output += line;
  }
   in.close();
   p.waitFor();
   return output;

} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}

该功能适用​​于其他命令

1 个答案:

答案 0 :(得分:1)

方法Runtime.exec(String prog, String[] envp, File directory)要求您在name=value中以String[] envp的形式提供环境。

但是您正在使用它将参数传递给您的php程序。

请改用以下方法,

Process exec (String[] progArray, String[] envp, File directory);

并在第一个数组中传递所有命令行参数。

您的命令应如下所示:

String[] progArray= {"./php", "-f", getFilesDir().getAbsolutePath()+"/phprun.php"}; // ">>","phpoutput.txt"
File dir=  new File(getFilesDir().getAbsolutePath());
Process p = Runtime.getRuntime().exec(progArray,null,dir);