如何使用 Java 打开命令提示符并插入命令? [英] How to open the command prompt and insert commands using Java?

查看:43
本文介绍了如何使用 Java 打开命令提示符并插入命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以打开命令提示符(我猜是其他系统的任何其他终端),并在新打开的窗口中执行命令吗?

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"});

我试过在开始"之后添加下一个命令,我试过运行另一个包含我的命令的 rt.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 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 打开命令提示符并插入命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆