Runtime.getRuntime.exec(String)与exec(String[])的区别

Runtime.getRuntime.exec(String) java

这个方法传入的是字符串,JAVA内部处理时会对字符串进行分割成数据,而后调用exec(String[],null,null)方法 ui

public Process exec(String command) throws IOException {
	return exec(command, null, null);
    }

public Process exec(String command, String[] envp, File dir)
        throws IOException {
        if (command.length() == 0)
            throw new IllegalArgumentException("Empty command");

	StringTokenizer st = new StringTokenizer(command);
	String[] cmdarray = new String[st.countTokens()];
 	for (int i = 0; st.hasMoreTokens(); i++)
	    cmdarray[i] = st.nextToken();
	return exec(cmdarray, envp, dir);

 public Process exec(String[] cmdarray, String[] envp, File dir)
	throws IOException {
	return new ProcessBuilder(cmdarray)
	    .environment(envp)
	    .directory(dir)
	    .start();
    }



Runtime.getRuntime.exec(String[])

该方法会最后也是执行exec(String[],null,null) code

public Process exec(String cmdarray[]) throws IOException {
	return exec(cmdarray, null, null);
    }

    public Process exec(String[] cmdarray, String[] envp, File dir)
	throws IOException {
	return new ProcessBuilder(cmdarray)
	    .environment(envp)
	    .directory(dir)
	    .start();
    }


从上面能够看出,若是执行一整条已经拼接好的命令时,能够用exec(String);若是命令参数分开时,能够用exec(String[]);若是把一条已经拼接好的字符串执行第二个方法,就会报命令找不到。 字符串

相关文章
相关标签/搜索