JAVA执行Linux命令+一个简单封装
2018-05-12 本文已影响0人
WESTWALL
执行多条命令
// ……
String command = "unzip " + newPath + " && " + "rm " + newPath;
Process process = Runtime.getRuntime().exec(new Stirng[]{"/bin/sh", "-c", command});
// ……
参考: https://blog.csdn.net/huanghai200911/article/details/46418121
一个简单封装
CommandUtil
/**
* 命令行工具
* @author JohnXi
*
*/
public class CommandUtil {
/**
* 执行命令行命令
* @param command
* @return MyProcess
* @throws Exception
*/
public static MyProcess exec(String command) throws Exception {
Process process = Runtime.getRuntime().exec(command);
return new MyProcess(process);
}
/**
*
* @param cmdarray
* @return
* @throws Exception
*/
public static MyProcess exec(String[] cmdarray) throws Exception {
Process process = Runtime.getRuntime().exec(cmdarray);
return new MyProcess(process);
}
}
MyProcess
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.mingyoutech.etl.commons.util.TextUtil;
/**
* 封装后的Process对象
* @author JohnXi
*
*/
public class MyProcess {
/**
*
*/
private Process process;
/** 是否存在错误输出 */
private boolean hasErrorStream;
/**
* 标准输出信息
*/
private StringBuffer messageBuffer = new StringBuffer();
/**
*
* @param process
*/
MyProcess(Process process) {
this.process = process;
final InputStream isInput = process.getInputStream();
final InputStream isErr = process.getErrorStream();
new Thread(new Runnable() {
public void run() {
BufferedReader brInput = new BufferedReader(new InputStreamReader(isInput));
BufferedReader brErr = new BufferedReader(new InputStreamReader(isErr));
try {
String message = "";
String error = "";
while ((message = brInput.readLine()) != null || (error = brErr.readLine()) != null) {
if (message != null && !message.isEmpty()) {
messageBuffer.append(message + TextUtil.getLineSeparator());
}
if (error != null && !error.isEmpty()) {
hasErrorStream = true;
messageBuffer.append(error + TextUtil.getLineSeparator());
}
}
} catch (Exception e) {
}
}
}).start();
}
/**
* 停止运行
*/
public void destroy() {
process.destroy();
}
/**
* 等待执行完毕
* @throws InterruptedException
*/
public void waitFor() throws InterruptedException {
process.waitFor();
}
/**
* 查看程序返回值
* @return
*/
public int exitValue() {
return process.exitValue();
}
/**
* 程序是否存在错误输出
* @return true-有错误输出
*/
public boolean hasErrorStream() {
return hasErrorStream;
}
/**
* 查看标准输出信息
* @return
*/
public String getMessage() {
return messageBuffer.toString();
}
}
example
String command = "";
if (".gz".equals(suffix)) {
command = "gunzip " + newPath;
} else if (".zip".equals(suffix)) {
// unzip命令:不会删除原压缩文件,所以需要手工删除
command = "unzip " + newPath + " && " + "rm " + newPath;
}
String[] cmdarray = new String[]{"/bin/sh", "-c", command};
// 在这里使用!
MyProcess process = CommandUtil.exec(cmdarray);
process.waitFor();
System.out.println("$? = " + process.exitValue() + ", message = " + process.getMessage());