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[]);若是把一條已經拼接好的字符串執行第二個方法,就會報命令找不到。 字符串

相關文章
相關標籤/搜索