[英]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.