Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

How to open the command prompt and insert commands using 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?

Currently what I have is this:

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

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

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.

question from:https://stackoverflow.com/questions/4688123/how-to-open-the-command-prompt-and-insert-commands-using-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...