我想从特定的文件夹中执行我的文件,例如在我的情况下是 /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)
方法指定工作目录来调用可执行文件,是可行的。
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
时看不到更改。
当我使用以下重载方法时,它对我有效:
public Process exec(String command, String[] envp, File dir)
例如:
File dir = new File("C:/Users/username/Desktop/Sample");
String cmd = "java -jar BatchSample.jar";
Process process = Runtime.getRuntime().exec(cmd, null, dir);
这个命令只是将你想要在命令行中运行的命令存储起来。而dir
则是存储要执行的.jar文件的路径。
cd flutter_app
flutter build apk
cd ..
而Java代码看起来像这样:
Process process = Runtime.getRuntime().exec("execute.bat");
....exec("/data/data/my-package/files/myfile");
这段代码能正常工作吗? - zapl