JAVA执行命令是命令错误_JAVA执行Linux命令报错Cannot run program error=2 , No such file or directory...

JAVA使用ProcessBuilder运行Linux命令报错: start failed:Cannot run program "xxx" (in directory "xx"): error=2, No such file or directory。

网上找了各种资料都没解决,最后想起azkaban的源码里也是用的ProcessBuilder来执行shell命令,于是翻了一下代码,找到了解决方案,把azkaban里的partitionCommandLine这个方法对command做一下处理,就ok了。

代码如下:

run_command(partitionCommandLine(command), work_path);

/**

*执行命令

*/

public boolean run_command(final String[] command, final File work_path) throws IOException, InterruptedException {

log.info("COMMAND:" + command);

List result_list = new ArrayList<>();

ProcessBuilder hiveProcessBuilder = new ProcessBuilder(command);

hiveProcessBuilder.directory(work_path);

hiveProcessBuilder.redirectErrorStream(true);

Process hiveProcess = hiveProcessBuilder.start();

BufferedReader std_input = new BufferedReader(new InputStreamReader(hiveProcess.getInputStream(), "UTF-8"));

BufferedReader std_error = new BufferedReader(new InputStreamReader(hiveProcess.getErrorStream(), "UTF-8"));

String line;

while ((line = std_input.readLine()) != null) {

result_list.add(line);

}

while ((line = std_error.readLine()) != null) {

log.error(line);

}

hiveProcess.waitFor();

if (hiveProcess.exitValue() != 0) {

log.error("failed to execute:" + command);

return false;

}

log.info("execute success:" + command);

IOUtils.closeQuietly(std_input);

IOUtils.closeQuietly(std_error);

return true;

}

/**

*对命令进行处理

*/

public static String[] partitionCommandLine(final String command) {

final ArrayList commands = new ArrayList<>();

int index = 0;

StringBuffer buffer = new StringBuffer(command.length());

boolean isApos = false;

boolean isQuote = false;

while (index < command.length()) {

final char c = command.charAt(index);

switch (c) {

case ' ':

if (!isQuote && !isApos) {

final String arg = buffer.toString();

buffer = new StringBuffer(command.length() - index);

if (arg.length() > 0) {

commands.add(arg);

}

} else {

buffer.append(c);

}

break;

case '\'':

if (!isQuote) {

isApos = !isApos;

} else {

buffer.append(c);

}

break;

case '"':

if (!isApos) {

isQuote = !isQuote;

} else {

buffer.append(c);

}

break;

default:

buffer.append(c);

}

index++;

}

if (buffer.length() > 0) {

final String arg = buffer.toString();

commands.add(arg);

}

return commands.toArray(new String[commands.size()]);

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值