有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

sqlite如何用Java编写adb shell命令

我想抽一些。来自安卓设备的db文件,用于自动化测试,需要

  1. 打开命令提示符 2.输入adb外壳命令, 下面是我想用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 ");
}
}

有人能推荐一下吗


共 (1) 个答案

  1. # 1 楼答案

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