Java执行Linux命令

简介: Java执行Linux命令
package org.ml.deployer.util;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
 
public class CommandUtil {
    public static String run(String command) throws IOException {
        Scanner input = null;
        String result = "";
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(command);
            try {
                //等待命令执行完成
                process.waitFor(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            InputStream is = process.getInputStream();
            input = new Scanner(is);
            while (input.hasNextLine()) {
                result += input.nextLine() + "\n";
            }
            result = command + "\n" + result; //加上命令本身,打印出来
        } finally {
            if (input != null) {
                input.close();
            }
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }
    
    public static String run(String[] command) throws IOException {
        Scanner input = null;
        String result = "";
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(command);
            try {
                //等待命令执行完成
                process.waitFor(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            InputStream is = process.getInputStream();
            input = new Scanner(is);
            while (input.hasNextLine()) {
                result += input.nextLine() + "\n";
            }
            result = command + "\n" + result; //加上命令本身,打印出来
        } finally {
            if (input != null) {
                input.close();
            }
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }
}
相关文章
|
3月前
|
Java Linux
Java执行Linux命令
Java执行Linux命令
|
3月前
|
Java 编译器 Windows
用命令行运行Java代码
用命令行运行Java代码
22 0
|
10月前
|
缓存 监控 网络协议
Java面试题 -Linux命令
Java面试题 -Linux命令
73 0
|
Java 应用服务中间件
Java——通过Java代码启动批处理文件(一)
Java——通过Java代码启动批处理文件(一)
Java——通过Java代码启动批处理文件(二)
Java——通过Java代码启动批处理文件(二)
|
Java 编译器
理解Java程序的执行
理解Java程序的执行
|
Java Shell Maven
Java执行shell命令
java执行shell命令的方式有很多种,但是在应用的过程中,我们可能会遇上一些特殊的情况,导致执行脚本失败,不生效的场景。
407 0
|
Java Linux
在java代码中使用linux指令
在java代码中使用linux指令
|
Java
执行以下操作安装 Java
执行以下操作安装 Java
92 0
|
Java
Java - 传带命令参数运行程序
Java - 传带命令参数运行程序
588 0
Java - 传带命令参数运行程序