首页 > 系统相关 >java执行linux语句

java执行linux语句

时间:2023-04-24 20:13:30浏览次数:36  
标签:语句 java process 命令 command linux new null out

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;
    }

  测试

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")));
}

  

  

标签:语句,java,process,命令,command,linux,new,null,out
From: https://www.cnblogs.com/action1/p/17350720.html

相关文章

  • Java中Runnable和Callable的区别 Runnable接口
    Callable接口从Java1.0开始,它是java.lang包的一部分从Java1.5开始,它是java.util.concurrent包的一部分。Runnable接口不能返回计算的结果。Callable接口可以返回一个任务的并行处理的结果。Runnable接口不能抛出一个有检查的异常。Callable接口可以抛出一个有检查的异常。......
  • java反序列化(五) JNDI注入
    JNDI注入前置知识JNDIJNDI(JavaNamingandDirectoryInterface)是一个应用程序设计的API,为开发人员提供了查找和访问各种命名和目录服务的通用、统一的接口。可以通过字符串来锁定一个对象JNDI支持的服务主要有以下几种:RMI(JAVA远程方法调用)LDAP(轻量级目录访问协......
  • Java中null和“”的区别
    null和空字符串('')虽然都是没有任何内容,但是null却输出空指针异常,因为堆内存中根本就没有这个东西。他们的区别可相当大,虽然都是没有信息,但是null代表堆内存中根本没有这个东西,这个对象不存在,怎么执行indexof操作?空字符串虽然没有信息,但是是有内存空间的,所以null与空字符串主要......
  • springboot mybatis 动态调用oracle存储过程,通过存储过程名称,就能动态调用存储过程、j
    由于在开发业务时,可能同时调用的存储过程不知道参数,但是参数从界面、或已经存储在数据库的获取,所以就不希望手动写存储过程的参数,通过简化的调用。能不能写个动态的业务,只输入存储过程名称,自动获取存储过程参数,并且参数的数据从前台传递过来,这个就通用了。只写一个通用方法,就可以......
  • Linux 压缩与解压
    Linux压缩与解压1.tar-z:有gzip属性的-v:显示所有过程-x:解压-c:压缩-f:指定解压的文件名,切记,这个参数是最后一个参数,后面只能接文件名实例:压缩文件(gzip)tar-zxvf[file]-C[path]解压文件(gzip)tar-zcvf[file]-C[path]列出压缩文件内容(gzip)tar-tzvftest.tar.......
  • Java 依赖注入(DI)
    只要做过Java一段时间,基本上都会遇到这个问题。DependencyInjection(DI)中文称之为依赖注入。都说了Spring的关键部分就是DependencyInjection(DI),但是什么是依赖,为什么要注入,基本上没怎么找到使用简单文字说明的本文尝试用土话把这个问题说明白。这里有2个概念,依赖和注入。......
  • java -- 注解
    注解注解概述定义:注解(Annotation),也叫元数据。一种代码级别的说明。它是JDK1.5及以后版本引入的一个特性,与类、接口、枚举是在同一个层次。它可以声明在包、类、字段、方法、局部变量、方法参数等的前面,用来对这些元素进行说明,注释。作用分类:编写文档:通过代码里标识的注解生成......
  • Java
    HashSetcontainsaddStack+emptypeekpoppush(add)sizeHashMapvalueOf(value)get(key),put(key,value),isEmpty()containsKey(key)containsValue(value)remove(key)cnt.merge(x,1,Integer::sum);QueueQueueq=newLinkedList<>();Priorit......
  • 云原生周刊:2023 年 Java 开发人员可以学习的 25 大技术技能
    文章推荐2023年Java开发人员可以学习的25大技术技能这篇文章为Java开发人员提供了2023年需要学习的一些重要技能,这些技能涵盖了现代Java开发、大数据和人工智能、安全性、分布式系统和区块链、以及其他领域。Java开发人员应该根据自己的需求和职业规划,选择适合自己......
  • JAVA下载图片压缩zip
    1.支持多张图片下载/***下载附件zip*/@PostMapping("downloadZip")publicvoiddownloadZip(@RequestBodyShipmentAnnexVoshipmentAnnexVo,HttpServletRequestrequest,HttpServletResponseresponse){shipmentAnnexService.downloadZip(shipmentAnnexVo,request,......