java执行linux命令

6,427 阅读1分钟

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

API

img

把要执行的命令作为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的脚本:

img

执行结果:

img

执行带特殊字符的命令

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

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

img

注意

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

以上就是良许教程网为各位朋友分享的Linux相关知识。