简体   繁体   中英

Runtime.getRuntime.exec() Error codes

I am trying to use runtime.getruntime.exec in a Java application.

For quite a while, I've been trying to run different command and I keep getting Error Code 2 which I've found to mean that the file or directory doesn't exist. To test, I attempted to pass a basic command and am getting Error Code 1. Why am I getting this and what does Error Code 1 mean?

Here is my code:

  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;

Here is how I call it:

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

Here is my output:

 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

Runtime.getRuntime().exec(command) is expecting an exe file as its first parameter in the passed string. Commands like ( cd, echo, etc... ) are specific for the Command Line Tool and will not work as directly passed commands. You will need to invoke the command line tool first and then pass your command as it's arguments:

// 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");

On a separate note. you will want to initialize your result to be an empty string instead of null. Otherwise the word "null" will be prepended to what your printing out.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM