java操作cmd执行adb命令【搬代码】

操作具体代码如下:
须注意的是commandStr0里面如果不加 cmd /的话会报

java.io.IOException: Cannot run program "cd": CreateProcess error=2, 系统找不到指定的文件。

的错误

package com.znzdh.until;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

public class Cmd {

    public static void main(String[] args) throws InterruptedException {
        System.out.println("开始");
        String commandStr0 = "cmd /cd E:\\appium\\android-sdk\\platform-tools";//进入该文件夹下面
        Cmd.exeCmd(commandStr0);
        System.out.println("进入tools");
        Thread.sleep(200);
        String commandStr1 = "adb -s 192.168.31.00:5555 shell am start -a android.media.action.IMAGE_CAPTURE --ei android.intent.extras.CAMERA_FACING 1";
        Cmd.exeCmd(commandStr1);
        System.out.println("打开相机");
        Thread.sleep(500);
        String commandStr2 ="adb -s 192.168.31.00:5555 shell screencap /sdcard/screen1.png";
        Cmd.exeCmd(commandStr2);
        System.out.println("截图保存相册");
        Thread.sleep(200);
        String commandStr3="adb -s 192.168.31.00:5555 pull /sdcard/screen1.png E:\\需求";
        Cmd.exeCmd(commandStr3);
        System.out.println("保存到E盘需求");
        Thread.sleep(200);
        String commandStr4="adb -s 192.168.31.00:5555 shell input keyevent 4";
        Cmd.exeCmd(commandStr4);
        System.out.println("退出相机");
        Thread.sleep(200);
        System.out.println("结束");
    }

    public static void exeCmd(String commandStr) {
        BufferedReader br = null;
        try {
            //执行cmd命令
            Process p = Runtime.getRuntime().exec(commandStr);
            //返回值是流,以便读取。
            br = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.forName("GBK")));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            System.out.println(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null){
                try {
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

操作结果:
java操作cmd执行adb命令【搬代码】_第1张图片

你可能感兴趣的:(java)