Java 在linux下shell执行工具类
Java 程序调用 linux命令 、脚本,支持程序在服务器上使用 linux命令 。 工具类 为:ShellUtil,支自己写的话,得考虑异常等其他地方, Java 运行 Linux命令命令工具类
package com.example.demomissyou.common.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
/**
* Created by YN on 2017/8/14 0014.
* shell脚本执行方法
*/
public class ShellUtil {
private static Logger log = LoggerFactory.getLogger(ShellUtil.class);
/**
* 执行shell脚本返回字符串
*
* @param cmd :linux命令
* @return 执行的结果字符串
*/
public static String exec(String cmd) {
//log.error("[ShellUtil--exec] cmd:" + cmd);
try {
String[] cmdA = {"/bin/sh", "-c", cmd};
Process process = Runtime.getRuntime().exec(cmdA);
process.waitFor();
LineNumberReader br = new LineNumberReader(new InputStreamReader(
process.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
//log.error("[ShellUtil--exec] result:" + sb.toString());
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 执行linux命令/shell脚本方法
*
* @param cmd:要执行的命令
* @return 提示码
*/
public static int exeShell(String cmd) {
//log.error("[ShellUtil--exec] cmd:" + cmd);
int code = -1;
try {
Process p = Runtime.getRuntime().exec(cmd);
code = p.waitFor();
} catch (Throwable e) {
e.printStackTrace();
}
//log.error("[ShellUtil--exec] returnCode:" + code);
return code;
}
/**
* 执行shell脚本返回退出码
*
* @param cmd :linux命令
* @return 执行的结果字符串
*/
public static int execCmd(String cmd) {
int code = -1;
try {
String[] cmdA = {"/bin/sh", "-c", cmd};
Process process = Runtime.getRuntime().exec(cmdA);
code = process.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
return code;
}
/**
* 执行shell脚本返回字符串数组
*
* @param cmd :linux命令
* @return 执行的结果字符串
*/
public static String[] execArray(String cmd) {
LineNumberReader br = null;
try {
String[] cmdA = {"/bin/sh", "-c", cmd};
Process process = Runtime.getRuntime().exec(cmdA);
process.waitFor();
br = new LineNumberReader(new InputStreamReader(process.getInputStream()));
String[] sb = new String[200];
String line;
int index = 0;
while ((line = br.readLine()) != null) {
sb[index++] = line;
}
return sb;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接