我想从android设备中提取一些.db文件用于自动化测试,需要
- 打开命令提示符2.输入adb shell命令,下面是我想用JAVA编程在命令提示符下编写的命令
adb shell
run-as com.sk.shaft
cd files
cp file.db /sdcard/download/sample.db3
exit
exit
adb pull /sdcard/download/sample.db3 C:/users/libin/desktop/sample.db
到目前为止,我可以打开命令提示符,但无法在命令提示符中输入以上命令。
public class DBExtract {
public static void main(String[] args) throws IOException {
Process process= Runtime.getRuntime().exec("cmd /c start cmd.exe /k ");
}
}
有人能建议一下吗?
运行多个命令。当打开cmd
窗口时,您将失去对它的控制。您可以创建一个批处理脚本,在新的cmd
窗口中运行它并重定向输入。
您可以在cmd.exe
的/k
参数之后传递批处理脚本。在批处理文件中,可以使用来自批处理的重定向。
实际上,您正在运行两个命令。adb shell
是一个命令,adb pull
是另一个命令。执行";子命令";在adb的shell中,使用process.getOutputStream()
,在其上创建OutputStreamWriter
并向其写入命令。
因此,为adb shell创建一个进程,将文本重定向到程序的输入,然后在另一个进程中使用adb pull
。
如果要查看命令的输出,请使用Process#getInputStream
。
程序可能看起来像这样:
public class DBExtract {
public static void main(String[] args) throws IOException {
Process process= Runtime.getRuntime().exec("adb shell");
try(PrintWriter pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(process,getOutputStream(),StandardCharsets.UTF_8)))){
pw.println("run-as com.sk.shaft");
pw.println("cd files");
pw.println("cp file.db /sdcard/download/sample.db3");
pw.println("exit");
pw.println("exit");
}
process=Runtime.getRuntime().exec("adb pull /sdcard/download/sample.db3 C:/users/libin/desktop/sample.db");
}
}