2012-04-18 131 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,所以它没有任何意义。