简体   繁体   English

如何在 Java 中编写 adb shell 命令

[英]How to write adb shell commands in Java

I wanted to pull some.db file from android device for automation testing which needs to我想从 android 设备中提取 some.db 文件进行自动化测试,需要

  1. Open Command prompt 2.enter the adb shell commands, below are the commands that i wanted to write in command prompt by programaticaly in JAVA,打开命令提示符 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

Till now i can open command prompt but i cant enter the above commands in the command prompt.到目前为止,我可以打开命令提示符,但无法在命令提示符中输入上述命令。

public class DBExtract {

    public static void main(String[] args) throws IOException {

Process process= Runtime.getRuntime().exec("cmd /c start cmd.exe /k ");
}
}

could anyone suggest please?有人可以建议吗?

Run multiple commands.运行多个命令。 When opening a cmd window you lose control over it.打开cmd window 时,您将失去对它的控制。 You could create a batch script, run it in a new cmd window and redirect the input.您可以创建一个批处理脚本,在新的cmd window 中运行它并重定向输入。

You can pass the batch script after the /k parameter of cmd.exe .您可以在cmd.exe/k参数之后传递批处理脚本。 In the batch file, you can use the redirection from batch.在批处理文件中,您可以使用批处理中的重定向。

You are actually running two commands.您实际上正在运行两个命令。 adb shell is one command and adb pull is another. adb shell是一个命令,而adb pull是另一个。 To execute "subcommands" in the shell from adb, use process.getOutputStream() , create an OutputStreamWriter on it and write the commands to it.要从 adb 执行 shell 中的“子命令”,请使用process.getOutputStream() ,在其上创建一个OutputStreamWriter并将命令写入其中。

So, create a process for adb shell, redirect text to the input of the program and then use adb pull in another process.因此,为 adb shell 创建一个进程,将文本重定向到程序的输入,然后在另一个进程中使用adb pull

If you want to see the output of the commands, use Process#getInputStream .如果要查看命令的 output,请使用Process#getInputStream

The program could look like this:该程序可能如下所示:

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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM