使用Runtime.getRuntime()。exec从定义的目录执行文件

我只想从特定文件夹执行我的文件。 在我的情况下/ data / data / my-package / files /。 所以我试过:

Process process2=Runtime.getRuntime().exec("cd /data/data/my-package/files/"); process2.waitFor(); process2=Runtime.getRuntime().exec("./myfile"); 

它不起作用。 请有人告诉我正确的方法。 谢谢

应该可以使用Runtime.exec(String command, String[] envp, File dir)使用特定的工作目录调用可执行Runtime.exec(String command, String[] envp, File dir)

如下:

 Process process2=Runtime.getRuntime().exec("/data/data/my-package/files/myfile", null, new File("/data/data/my-package/files")); 

也许没有myfile的完整路径

 Process process2=Runtime.getRuntime().exec("myfile", null, new File("/data/data/my-package/files")); 

Context#getFilesDir()而不是硬编码路径也应该工作,并且比自己指定路径更安全/更清洁,因为不能保证/data/data/..始终是所有设备的正确路径。

 Process process2=Runtime.getRuntime().exec("myfile", null, getFilesDir())); 

cd somewhere的问题是为不同的进程更改了目录,因此在新进程中第二次调用exec时看不到更改。