繁体   English   中英

从资源链接ADB路径以在Java应用程序中执行Shell命令

[英]Link adb path from resource to execute shell commands in Java application

我正在寻找一种直接从Java应用程序运行adb命令的方法。 在Stack Overflow上进行搜索时,我发现了以下用于运行Shell命令的解决方案,

public class Utils {
    private static final String[] WIN_RUNTIME = {"cmd.exe", "/C"};
    private static final String[] OS_LINUX_RUNTIME = {"/bin/bash", "-l", "-c"};

    private Utils() {
    }

    private static <T> T[] concat(T[] first, T[] second) {
        T[] result = Arrays.copyOf(first, first.length + second.length);
        System.arraycopy(second, 0, result, first.length, second.length);
        return result;
    }

    public static List<String> runProcess(boolean isWin, String... command) {
        System.out.print("command to run: ");
        for (String s : command) {
            System.out.print(s);
        }
        System.out.print("\n");
        String[] allCommand = null;
        try {
            if (isWin) {
                allCommand = concat(WIN_RUNTIME, command);
            } else {
                allCommand = concat(OS_LINUX_RUNTIME, command);
            }
            ProcessBuilder pb = new ProcessBuilder(allCommand);
            pb.redirectErrorStream(true);
            Process p = pb.start();
            p.waitFor();
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String _temp = null;
            List<String> line = new ArrayList<String>();
            while ((_temp = in.readLine()) != null) {
                //System.out.println("temp line: " + _temp);
                line.add(_temp);
            }
            System.out.println("result after command: " + line);
            return line;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
} 

这完美地工作,但是我找不到将adb.exe路径添加到shell命令中以便执行adb命令的解决方案。

我的项目结构如下

在此处输入图片说明

我正在尝试使用以下方式将adb路径与系统默认的shell路径一起添加,

Utils.runProcess(true, "/resources/adb.exe devices");

有没有办法将资源中的adb.exe路径附加到shell命令中?

以这种方式使用adb.exe的完整路径,而无需将其添加到%PATH%

例如。 如果打开cmd并运行C:\\...\\adb.exe devices ,它将正常工作

或者在外壳中执行此命令来设置路径,

setx path "%path%;C:\..."

编辑:adb.exe添加到resources文件夹中与调用类相同的包中。 然后将其加载并将其写入您碰巧知道的其他位置(或生成相对于jar所在位置的路径,例如System.getProperty("user.dir" );)

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("adb.exe").getFile());
// now copy this file to a location you already know eg. C:\...\temp\adb.exe

然后使用您拥有的路径调用adb.exe

暂无
暂无

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

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