java - 如何在 Java 中编写 adb shell 命令
问题描述
我想从 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
窗口中运行它并重定向输入。
/k
您可以在 的参数之后传递批处理脚本cmd.exe
。在批处理文件中,您可以使用批处理中的重定向。
您实际上正在运行两个命令。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");
}
}
推荐阅读
- python - 不允许 Django REST 框架 ModelSetView POST
- java - JAVA将两个流处理成一个映射
- mysql - mysql数据库仅允许从特定ip进行外部访问ubuntu 16
- r - 使用 R tidyverse 将条件均值均值保存为对象
- qt - 有没有办法在 qml 中使用图像占位符?
- r - 地图中的谓词函数
- c++ - 为什么我的窗口被 wxBoxSizer 调整为小于其最小尺寸
- python - 蟒蛇,硒 | 不能点击这里测试
- swift - 使用“userNotificationCenter willPresent notification: UNNotification”我的电脑速度非常慢
- c++ - 在 C++ 中实现字母表