Java执行Linux命令 - Go语言中文社区

Java执行Linux命令


最近工作中需要在Java中执行Linux命令,对遇到的坑做一个小结。

API


把要执行的命令作为exec方法的参数,返回一个Process对象代表命令执行的进程。由于执行完命令通常要获取输出显示出来,因此对执行命令并获取输出的过程封装为一个工具类:

CommandUtil

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

示例:

执行启动tomcat的脚本:


执行结果:


执行带特殊字符的命令

exec方法无法执行带 | > 等特殊字符的命令,如 ps -ef | grep java 。

此时要把整个命令作为 /bin/sh 的参数执行,如:


注意

exec方法通过创建一个子进程执行Linux命令,因此频繁地通过Java调用Linux命令对性能影响非常大,不要在程序中过度使用这种方式。

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_21508059/article/details/80334910
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-06-28 02:36:14
  • 阅读 ( 1008 )
  • 分类:Linux

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢