问题描述
是否可以打开命令提示符(我猜其他系统的任何其他终端),并在新打开的窗口中执行命令?
Is it possible to open the command prompt (and I guess any other terminal for other systems), and execute commands in the newly opened window?
目前我拥有的是:
Runtime rt = Runtime.getRuntime();
rt.exec(new String[]{"cmd.exe","/c","start"});
我试过在开始之后添加下一个命令, .exec包含我的命令,但我找不到一种方法使其工作。
I've tried adding the next command after the "start", I've tried running another rt.exec containing my command, but I can't find a way to make it work.
如果重要,我尝试运行类似如下的命令:
If it matters, I'm trying to run a command similar to this:
java -flag -flag -cp terminal-based-program.jar
EDIT 不幸的是,我有一些奇怪的发现。我已经能够成功地启动命令提示符并使用以下命令传递命令:
EDIT Unfortunately I have had some strange findings. I've been able to successfully launch the command prompt and pass a command using this:
rt.exec("cmd.exe /c start command");
但是,它似乎只能使用一个命令。因为,如果我尝试使用这样的命令分隔符,cmd.exe / c start command& command2,第二个命令通过后台(如果我只是使用rt.exec(command2), ;)。现在这里的问题是,我意识到我需要更改命令提示符运行的目录,因为如果我只是使用jar文件的完整路径,jar文件不正确地从命令提示符的活动目录中读取数据,而不是该jar包含其资源的目录。
However, it only seems to work with one command. Because, if I try to use the command separator like this, "cmd.exe /c start command&command2", the second command is passed through the background (the way it would if I just used rt.exec("command2");). Now the problem here is, I realized that I need to change the directory the command prompt is running in, because if I just use the full path to the jar file, the jar file incorrectly reads the data from the command prompt's active directory, not the jar's directory which contains its resources.
推荐答案
我知道,人们建议远离rt.exec(String),但这是行得通的,我不知道如何将其更改为数组版本。
I know that people recommend staying away from rt.exec(String), but this works, and I don't know how to change it into the array version.
rt.exec("cmd.exe /c cd \""+new_dir+"\" & start cmd.exe /k \"java -flag -flag -cp terminal-based-program.jar\"");
这篇关于如何打开命令提示符并使用Java插入命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!