Alternative to java.lang.Runtime.exec() that can execute command lines as a single string?

我怕爱的太早我们不能终老 提交于 2019-12-25 07:45:16

问题


I am calling java.lang.Runtime.exec(...) but this seems to accept the command lines as an array and I want to use a single string.

How can I do the same using a single string?


回答1:


From the linked Javadocs:

envp - array of strings, each element of which has environment variable settings in the format name=value, or null if the subprocess should inherit the environment of the current process.

So just pass in null for the second parameter, and the environment will be inhereted.




回答2:


If you pass null for the second paramter the current environment will be inherited.

If you want to modify the current environment, you can build it from System.getEnv() like this:

private static String[] getEnv() {
    Map<String, String> env = System.getenv();
    String[] envp = new String[env.size()];
    int i = 0;
    for (Map.Entry<String, String> e : env.entrySet()) {
        envp[i++] = e.getKey() + "=" + e.getValue();
    }
    return envp;
}

Update

You can check your Java path with System.out.println(System.getenv("PATH"));

If path is ok, then try it with

String[] commands = new String[] { "bash", "-c", "python foo/bar.py" };
Runtime.getRuntime().exec(commands, null, new File("/workingDir"));



回答3:


From the documentation:

envp - array of strings, each element of which has environment variable settings in the format name=value, or null if the subprocess should inherit the environment of the current process.

It sounds like you want to pass null for that argument.




回答4:


Currently there is no way of calling a system command with a command line as a single string and be able to specify the current directory.

It seems that Java API is missing this basic feature :)

The workaround is to use the array version instead of string.



来源:https://stackoverflow.com/questions/10853719/alternative-to-java-lang-runtime-exec-that-can-execute-command-lines-as-a-sing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!