java执行linux语句
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | public class CommandUtil { /** * 在指定路径下执行一条命令,不能执行cd之类的命令 * * @param command 要执行的Linux命令 * @param dir 目标路径,在该路径执行上述Linux命令 * @return 命令执行后显示的结果 * @throws IOException */ public static String run(String command, File dir) throws IOException { Scanner input = null ; StringBuilder result = new StringBuilder(command + "\n" ); // 加上命令本身 Process process = null ; try { process = Runtime.getRuntime().exec(command, null , dir); try { //等待命令执行完成 process.waitFor(10, TimeUnit.MINUTES); } catch (InterruptedException e) { e.printStackTrace(); } InputStream is = process.getInputStream(); input = new Scanner( is ); while (input.hasNextLine()) { result.append(input.nextLine() + "\n" ); } } finally { if (input != null ) { input.close(); } if (process != null ) { process.destroy(); } } return result.toString(); } /** * 在指定路径下,开启脚本,可以执行多条命令 * * @param command 要执行的Linux命令 * @param dir 目标路径,在该路径执行上述Linux命令 * @return 所有命令执行后显示的结果 * @throws IOException */ public static List<String> run(String[] command, File dir) throws IOException { BufferedReader in = null ; PrintWriter out = null ; List<String> resultList = new ArrayList<String>(); Process process = null ; try { // 开启脚本是为了能够获取所有的返回结果 process = Runtime.getRuntime().exec( "/bin/sh" , null , dir); // /bin/sh开启shell脚本 in = new BufferedReader( new InputStreamReader(process.getInputStream())); out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(process.getOutputStream())), true ); for (String cmd : command) { out .println(cmd); // 一条条执行命令 } out .println( "exit" ); // 表示脚本结束,必须执行,否则in流不结束。 try { // 等待命令执行完成 process.waitFor(10, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } // 装填返回结果,比如ls命令执行后显示的一行行字符串 String line = "" ; while ((line = in .readLine()) != null ) { resultList.add(line); } resultList.add(0, Arrays.toString(command)); // 加上命令本身,可根据需要自行取舍 } finally { if ( out != null ) { out .close(); } if ( in != null ) { in .close(); } if (process != null ) { process.destroy(); } } return resultList; } |
测试
1 2 3 4 | public static void main(String[] args) throws IOException { String jarCommand = "mvn clean package -T 1C -Dmaven.test.skip=true -Dmaven.compile.fork=true" ; // 打包命令,忽略测试类 System.out.println(run(jarCommand, new File( "/Users/code/other/master" ))); } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端