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;
    }
}
目录
相关文章
|
21天前
|
Linux 网络安全 Python
linux后台运行命令screen的使用
linux后台运行命令screen的使用
56 2
linux后台运行命令screen的使用
|
21天前
|
Ubuntu Linux
查看Linux系统架构的命令,查看linux系统是哪种架构:AMD、ARM、x86、x86_64、pcc 或 查看Ubuntu的版本号
查看Linux系统架构的命令,查看linux系统是哪种架构:AMD、ARM、x86、x86_64、pcc 或 查看Ubuntu的版本号
143 3
|
17天前
|
机器学习/深度学习 安全 网络协议
Linux防火墙iptables命令管理入门
本文介绍了关于Linux防火墙iptables命令管理入门的教程,涵盖了iptables的基本概念、语法格式、常用参数、基础查询操作以及链和规则管理等内容。
177 73
|
10天前
|
Linux Shell
Linux 中 Tail 命令的 9 个实用示例
Linux 中 Tail 命令的 9 个实用示例
38 6
Linux 中 Tail 命令的 9 个实用示例
|
15天前
|
Linux 应用服务中间件 nginx
|
2天前
|
机器学习/深度学习 存储 Linux
linux中强大且常用命令:find、xargs、grep
linux中强大且常用命令:find、xargs、grep
24 9
|
2天前
|
SQL 移动开发 Linux
linux下find、grep命令详解
linux下find、grep命令详解
29 8
|
9天前
|
存储 Linux 编译器
linux中vim介绍以及常用命令大全
linux中vim介绍以及常用命令大全
31 8
|
6天前
|
设计模式 Java Linux
Linux的20个常用命令
Linux的23个常用命令
Linux的20个常用命令
|
11天前
|
机器学习/深度学习 安全 网络协议
Web安全-Linux网络命令
Web安全-Linux网络命令
12 1