Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to execute windows commands in Java in a "batch" manner? ie One after the other but kept persistent?

I'm looking to create a Java Application that is able to run windows commands in a "batch" manner; what I mean by this is that it's persistent in between commands and isn't as if you're only executing one at a time.

An example of this might be:

@echo off
pushd C:\foldertobepushedto\
call batchfiletobecalled.bat
popd
pushd anotherdirectorytobepushedinto
call anotherbatchfiletobecalled.bat
popd

I would like to be able to use the Process process = Runtime.getRuntime().exec(CMD); manner to be able to run each of these lines but kept persistent so that it's not as if each line is run completely separate from the rest of them.

I hope I am making a bit of sense; I intend to essentially remove the use of batch files all together and store each line as an element in a vector/array and execute them "batch" style that way.

like image 230
Kane Charles Avatar asked Jan 17 '26 17:01

Kane Charles


1 Answers

Excuse me. I know a way to solve this problem in JScript; I ignore if there is an equivalent method for Java.

You may achieve the desired effect you want if you:

Execute CMD.EXE file alone with NO parameters, but via WshShell.Exec method:

var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("cmd");

WshShell.Exec method provide access to the process standard I/O channels.

After that, send to the process' STDIN channel the commands you want to execute:

oExec.Stdin.WriteLine("@echo off");
oExec.Stdin.WriteLine("pushd C:\foldertobepushedto\");
oExec.Stdin.WriteLine("call batchfiletobecalled.bat");
oExec.Stdin.WriteLine("popd");
oExec.Stdin.WriteLine("exit");

This way, all commands will be executed in a way entirely equivalent as if they would be included in a Batch file. The only difference is that certain commands will not be correctly executed, like GOTO.

like image 114
Aacini Avatar answered Jan 20 '26 07:01

Aacini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!