* 执行一个shell命令,并返回字符串值* @param cmd 命令名称和参数数组(例如:{"/system/bin/cat", "/proc/version"})* @param workdirectory 命令执行路径(例如:"system/bin/")* @return 执行结果组成的字符串* @throws IOExceptionpublic static synchronized String run(String[] cmd, String workdirectory) throws IOException {StringBuffer result = new StringBuffer();try {// 创建操作系统进程或使用Runtime.exec()启动新进程ProcessBuilder builder = new ProcessBuilder(cmd);builder.directory(new File(workdirectory));// 合并标准错误和标准输出builder.redirectErrorStream(true);Process process = builder.start();// 读取进程的标准输出流InputStream in = process.getInputStream();byte[] buffer = new byte[1024];int length;while ((length = in.read(buffer)) != -1) {result.append(new String(buffer, 0, length));}// 关闭输入流if (in != null) {in.close();}} catch (Exception ex) {ex.printStackTrace();}return result.toString();}
Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号