Runtime.getRuntime.exec()错误代码

时间:2017-11-30 19:45:51

标签: java

我正在尝试在Java应用程序中使用runtime.getruntime.exec。

很长一段时间,我一直在尝试运行不同的命令,我一直收到错误代码2,我发现这意味着文件或目录不存在。为了测试,我试图传递一个基本命令并得到错误代码1.为什么我得到这个以及错误代码1是什么意思?

这是我的代码:

  private String executeCommand(String command) {
    logger.info("executing command : " + command);
    String result = null;
    try {
        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec(command);

        BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
        String line = null;

        while ((line = input.readLine()) != null) {
            result = result + line;
        }

        while ((line = stdError.readLine()) != null) {
            result = result + line;
        }
        int exitVal = pr.waitFor();
        System.out.println("Exited with error code " + exitVal);


    } catch (IOException e) {
        e.printStackTrace();
    } catch (NumberFormatException e) {
        e.printStackTrace();
    } catch (Throwable e) {
        e.printStackTrace();

    }
    logger.info("This is the result:" + result);
    return result;

以下是我的称呼方式:

 String temp = executeCommand("cd $HOME/my-directory/my-subdirectory");

这是我的输出:

 INFO : programname - executing command : cd $HOME/my-directory/my-
        subdirectory
 Exited with error code 1
 INFO : programname - This is the result:null/usr/bin/cd[8]: $HOME/my-
        directory/my-subdirectory:  not found

2 个答案:

答案 0 :(得分:1)

Runtime.getRuntime().exec(command)期待一个exe文件作为传递字符串中的第一个参数。像(cd, echo, etc...)这样的命令特定于命令行工具,不能用作直接传递的命令。您需要先调用命令行工具,然后将命令作为参数传递:

// Invoke Command Line Tool (.exe is optional) (cmd for windows sh for Linux)
// 1st argument indicates you want to run a command (/C for windows -c for Linux)
// 2nd argument is the cmd line command to run (echo)
Runtime.getRuntime().exec("cmd.exe /C echo helloworld");
Runtime.getRuntime().exec("sh -c echo helloworld");

单独说明。您需要将结果初始化为空字符串而不是null。否则,“null”这个词将被添加到您的打印之前。

答案 1 :(得分:0)

执行Process pr = rt.exec("cmd /c "+command);