DeltaDrizz
DeltaDrizz

Reputation: 51

Java Execute something in Process

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.

Upvotes: 2

Views: 87

Answers (3)

vlp
vlp

Reputation: 8116

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()).

Upvotes: 1

Irfan Khan
Irfan Khan

Reputation: 402

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

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201409

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().

Upvotes: 1

Related Questions