我试图通过代码获取adb设备列表,但在启动ProcessBuilder时遇到异常。
这是我的代码 - >
try {
ProcessBuilder pb = new ProcessBuilder("adb.exe", "adb devices");
pb.directory(new File("C:\\Users\\user\\AppData\\Local\\Android\\sdk\\platform-tools"));
Process p = pb.start(); // here is the xception
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
Pattern pattern = Pattern.compile("^([a-zA-Z0-9\\-]+)(\\s+)(device)");
Matcher matcher;
while ((line = in.readLine()) != null) {
if (line.matches(pattern.pattern())) {
matcher = pattern.matcher(line);
if (matcher.find())
System.out.println(matcher.group(1));
}
}
以下是异常堆栈跟踪 - >
java.io.IOException:无法运行程序“adb.exe”(在目录中 “C:\用户\用户名\应用程序数据\本地\ Android的\ SDK \平台工具”): CreateProcess error = 2,系统找不到指定的文件 java.lang.ProcessBuilder.start(未知来源)at MainTest.Example.main(Example.java:45)引起:java.io.IOException: CreateProcess error = 2,系统找不到指定的文件 java.lang.ProcessImpl.create(Native Method)at java.lang.ProcessImpl。(未知来源)at java.lang.ProcessImpl.start(未知来源)......另外2个
我在ProcessBuilder中更改命令后尝试过,但没有运气。
请帮助。
答案 0 :(得分:3)
这应该有效
ProcessBuilder pb = new ProcessBuilder("C:\\Users\\<your user name>\\AppData\\Local\\Android\\sdk\\platform-tools\\adb.exe", "adb devices");
不要忘记:
<your user name>
- 设置你的姓名
或将C:\Users\<your user name>\AppData\Local\Android\sdk\platform-tools\
放入windows PATH
变量。
答案 1 :(得分:2)
经过Vyacheslav对聊天的大量帮助和建议,这是社区的工作解决方案 - &gt;
try
{
ProcessBuilder pb = new ProcessBuilder("C:\\Users\\<Your User Name Here>\\AppData\\Local\\Android\\sdk\\platform-tools\\adb.exe", "devices");
//pb.redirectErrorStream(true); // can use these 2 line if you want to see output or errors in file.
//pb.redirectOutput(new File("C:/pbOutput.Txt"));
Process p = pb.start();
while(p == null)
Thread.sleep(1000);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
Pattern pattern = Pattern.compile("^([a-zA-Z0-9\\-]+)(\\s+)(device)");
Matcher matcher;
while ((line = in.readLine()) != null) {
if (line.matches(pattern.pattern())) {
matcher = pattern.matcher(line);
if (matcher.find())
System.out.println(matcher.group(1));
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
我只需要找出为什么“adb设备”不起作用。