Reputation: 105
I want to start a cmd command, then after the first command is done, I want to run a code to adjust some text in a file, then execute another command on the same cmd window. I don't know how to do that and everywhere I looked the answer is for the commands after each other which is not this case. the code for editing the text works fine without starting the cmd but if I execute the cmd command it does not change. code below.
public static void main(String[] args)throws IOException
{
try
{
Main m1 = new Main();
Process p= Runtime.getRuntime().exec("cmd /c start C:/TERRIERS/terrier/bin/trec_setup.bat");
p.waitFor();
/*code to change the text*/
m1.answerFile(1);
m1.questionFile(1);
/**********************/
//code to add another command here (SAME WINDOW!)
/************************/
}
catch(IOException ex){
}
catch(InterruptedException ex){
}
Upvotes: 1
Views: 493
Reputation:
Execute cmd
and send your command lines (.bat) to the standard input.
Process p = Runtime.getRuntime().exec("cmd");
new Thread(() -> {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null)
System.out.println(line);
} catch (Exception e) {
e.printStackTrace();
}
}).start();
try (PrintStream out = new PrintStream(p.getOutputStream())) {
out.println("C:/TERRIERS/terrier/bin/trec_setup.bat");
out.println("another.bat");
// .....
}
p.waitFor();
Upvotes: 3
Reputation: 269837
For starters, the \C
option terminates CMD
after executing the initial command. Use \K
instead.
You won't be able to use waitFor()
to detect when the initial command is done, because if you wait until the CMD
terminates, you won't be able to re-use the same process.
Instead, you'll need to read the output of CMD
process to detect when the batch file is complete and you are prompted for another command. Then write the next command line that you want to execute though the input stream of the Process
.
Sounds like a pain. Why would do you need to use the same window?
Upvotes: 2