使用Runtime.getRuntime().exec从定义的目录中执行文件 [英] execute file from defined directory with Runtime.getRuntime().exec
问题描述
我只想从特定文件夹执行文件.就我而言/data/data/my-package/files/. 所以我尝试了:
I just want to execute my file from a specific folder. in my case /data/data/my-package/files/. So i tried :
Process process2=Runtime.getRuntime().exec("cd /data/data/my-package/files/");
process2.waitFor();
process2=Runtime.getRuntime().exec("./myfile");
它不起作用.谁能告诉我正确的做法.谢谢
It doesn't work. could anyone tell me please the right way to do that . Thanks
推荐答案
It should be possible to call the executable with a specific working directory using 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/..
始终是所有设备的正确路径.
Context#getFilesDir()
instead of hardcoding the path should work too and is safer / cleaner than specifying the path yourself since it is not guaranteed that /data/data/..
is always the correct path for all devices.
Process process2=Runtime.getRuntime().exec("myfile",
null, getFilesDir()));
cd somewhere
的问题在于,已为其他Process更改了目录,因此在新Process中第二次调用exec
时看不到更改.
The problem with cd somewhere
is that the directory is changed for a different Process so the second call to exec
in a new Process does not see the change.
这篇关于使用Runtime.getRuntime().exec从定义的目录中执行文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!