2

I have the following code:

builder = new ProcessBuilder("cmd");
builder.inheritIO();
p = builder.start();
p.waitFor();

And in the created commandline, I would like to write e.g. "dir". How is this possible?

Best regards

Edit: I have to run multiple commands and I can't use multiple cmds for that.

3 Answers 3

1

Can't you just use something like this:

ProcessBuilder builder = new ProcessBuilder("cmd");
Process p = builder.start();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream));
for(int i=0;i<7;i++) {
    writer.write("dir"); 
    writer.newLine(); 
    writer.flush();
}
// Now terminate
writer.write("exit"); 
writer.newLine(); 
writer.flush();
p.waitFor();

To read the output, use p.getOutputStream() (and p.getErrorStream() if you want to -- also consider the ProcessBuilder.redirectErrorStream()).

Sign up to request clarification or add additional context in comments.

Comments

1

CMD.exe on the Windows Command site says (in part),

Options

/C     Run Command and then terminate

So, you should be able to use

cmd /C dir

But it's probably a better idea to prefer a pure Java solution using File.list().

2 Comments

But I have to run multiple commands and I can't use multiple cmds for that.
Create a batch, shell or cmd file and execute that.
0

See http://www.java-tips.org/java-se-tips-100019/88888889-java-util/426-from-runtimeexec-to-processbuilder.html

 Runtime runtime = Runtime.getRuntime();
 Process process = runtime.exec(command);

1 Comment

But I have to run multiple commands and I can't use multiple cmds for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.