调用系统的DOS命令方法执行需要的命令

本文介绍了一个用于执行命令行命令的实用工具类,该工具能够跨平台地执行DOS或Shell命令,并返回执行结果。文章提供了详细的代码实现,包括如何设置工作目录、合并错误输出与标准输出等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



package com.huaweisymantec.core.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* 命令行命令执行工具类
*
* @author s00108907
*
*/
public final class CommandUtils {

private static final Logger LOG = LoggerFactory.getLogger(CommandUtils.class);

/**
* 调用系统的DOS命令方法执行需要的命令
*
* @param command 要执行的命令
* @return 执行结果
* @throws IOException
*/
public static String exec(String command) throws IOException {
return exec(null, command);
}

/**
* 调用系统的DOS命令方法执行需要的命令
*
* @param directory 此进程的工作目录
* @param command 要执行的命令
* @return 执行结果
* @throws IOException
*/
public static String exec(String directory, String command) throws IOException {
InputStream in = null;
Reader reader = null;
BufferedReader br = null;
try {
ProcessBuilder pb;
if (System.getProperty("os.name").indexOf("Windows") == -1) {
pb = new ProcessBuilder("/bin/sh", "-c", command);
} else {
pb = new ProcessBuilder("cmd", "/c", command);
}
if (StringUtils.isNotBlank(directory)) {
pb.directory(new File(directory));
}
// merge the error output with the standard output
pb.redirectErrorStream(true);

LOG.debug("Now exceuting:{}", command);
Process p = pb.start();
in = p.getInputStream();
reader = new InputStreamReader(in, "gb2312");
br = new BufferedReader(reader);
StringBuffer lines = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
lines.append(line).append("\r\n");
}
LOG.debug("Exceuting result:{}", lines.toString());
return lines.toString();
} finally {
if (reader != null) {
reader.close();
}
if (br != null) {
br.close();
}
if (in != null) {
in.close();
}
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值