2012-04-18 133 views
1

我想用Java創建一個完整的交叉平臺控制檯。Java - 執行控制檯

我遇到的問題是當我使用cd命令時,路徑被重置。例如,如果我執行cd bin,然後cd ../,我將執行從我的應用程序的目錄中的第一個和第二個完全從同一目錄。

如果我想要去一個特定的文件夾,並執行一個程序我必須做這樣的事情:

cd C:\mydir & cd bin & start.exe

我想要做的是在不同的部分拆分此CMD:

cd C:\mydir然後cd bin然後start.exe

我怎麼能這樣做?有沒有辦法存儲當前的cd路徑並使用它呢?


這裏是我使用的代碼:

String[] cmd_exec = new String[] {"cmd", "/c", cmd}; 

Process child = Runtime.getRuntime().exec(cmd_exec); 

BufferedReader in = new BufferedReader(new InputStreamReader(child.getInputStream())); 
StringBuffer buffer = new StringBuffer(); 
buffer.append("> " + cmd + "\n"); 

String line; 
while ((line = in.readLine()) != null) 
{ 
    buffer.append(line + "\n"); 
} 
in.close(); 
child.destroy(); 
return buffer.toString(); 

它執行的命令,然後返回控制檯的內容。 (這是用於目前的窗口)。

回答

1

感謝Mads,我能夠做的伎倆:

這裏是我使用的代碼:

if (cmd.indexOf("cd ") >= 0) 
{ 
    String req_cmd = cmd.substring(0, 3); 
    String req_path = cmd.substring(3); 
    if (req_path.startsWith(File.separator) || req_path.substring(1, 2).equals(":")) 
     path = req_path; 
    else 
     if (new File(path + cmd.substring(3)).exists()) 
      path += cmd.substring(3); 
     else return "[Error] Directory doesn't exist.\n"; 

    if (!path.endsWith(File.separator)) path += File.separator; 

    cmd = req_cmd + path; 
} 
else cmd = "cd " + path + " & " + cmd; 

然後你就可以執行命令調用:

Runtime.getRuntime().exec(new String[] {"cmd", "/c", cmd}); 

唐忘記在你的班級中添加此屬性:

private static String path = System.getProperty("user.dir") + File.separator; 
1

如果你做CD你不想執行它。您只是想檢查相對路徑是否存在,然後將

File currentDir 

更改爲該目錄。所以我建議你將命令分成三部分:cd,dir/ls和其他東西。正如我所提到的那樣,cd通過使用File currentDir來更改目錄,dir應該只是獲取currentDir的文件夾和文件並列出它們,然後按照您所知的方式執行其餘的部分。請記住,您可以通過「」.split(「&」)分割命令字符串。這樣你可以做「cd C:\ mydir & cd bin & start.exe」.split(「&」); => {「cd C:\ mydir」,「cd bin」,「start.exe」}然後您可以按順序執行它們。

祝你好運。

2

如果要從特定目錄運行命令,請使用ProcessBuilder而不是Runtime.exec。在開始此過程之前,您可以使用directory方法來設置工作目錄。不要試圖使用cd命令 - 你沒有運行一個shell,所以它沒有任何意義。