首页 > 解决方案 > 如何在 Java 中编写 adb shell 命令

问题描述

我想从 android 设备中提取一些 .db 文件进行自动化测试,这需要

  1. 打开命令提示符 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 ");
}
}

有人可以建议吗?

标签: javasqliteappium-android

解决方案


运行多个命令。打开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");
    }
}

推荐阅读