首先,一些背景。在任何 Posix 系统上,在 shell 中,有两种类型的命令:
- 内部命令 (pwd,cd,echo)
- 外部命令(ls、cp、mv,有时还有 echo)
所有目录上下文命令(cd、pwd 等)都是在 shell 内实现的命令,因此如果要保留更改(例如,cd /data/local/tmp),则需要 shell 保持运行。
另一方面,外部命令是独立的,可以独立运行,但从它们的父进程(大多数情况下,shell)获取它们的目录上下文。
现在来解决问题。是的,使用脚本是个好主意,但实施起来很痛苦,因为它需要文件编辑的开销。但是,我们可以使用 shell 动态创建脚本并使用-c选项执行它。例如:
/system/bin/sh -c 'cd /data/local/tmp; touch abc; cp abc def; cd /; rm /data/local/tmp/abc'
在夏天:
String sPrefix="/system/bin/sh -c 'cd someplace;";
String sInputCmd=getCommand(); // this is simulating your command input
String sPostfix="'";
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(sPrefix+sInputCmd+sPostfix); // sh -c 'cd someplace; echo do something'
InputStream is = proc.getInputStream();
然而,这并没有给我们设置目录上下文的能力,所以我们需要模拟它。可以使用 Runtime.exec(String command, String[] envp, File dir) 方法添加目录上下文。有了这个,我们就有可能在命令之间维护目录上下文。但我们实际上如何做到这一点?一种解决方案是附加pwd到命令并将输出的最后一行作为新的目录上下文。因此
String sPath = "/"; // start in root directory
String sPrefix = "/system/bin/sh -c 'cd someplace;";
String sInputCmd; // this is simulating your command input
String sPostfix = ";echo;pwd'";
Runtime rt = Runtime.getRuntime();
while(!(sInputCmd=getCommand()).equals("")) {
File dir= new File(sPath);
Process proc = rt.exec(sPrefix+sInputCmd+sPostfix, NULL, dir);
InputStream is = proc.getInputStream();
// Do processing on input.
sPath= last_line_of_is ;
}
最后,最后一个选项是将其中一个终端仿真器集成到您的应用程序中。
[1] http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html#exec%28java.lang.String,%20java.lang.String%5B%5D,%20java .io.文件%29