Reputation: 609
I need to programmatically open a console (in windows) and from there I need to execute a large command in the console just created. I tried to write to the output stream but had no luck. Here is the code I have thus far to bring up the console.
File fileOne = new File(args[0]);
String[] command = { "cmd", "/c", "Start"};
ProcessBuilder procBuilder = new ProcessBuilder(command);
procBuilder.directory(fileOne);
Upvotes: 0
Views: 1513
Reputation: 13222
Here is an example I used to create a launch icon for a program.
Runtime rt = Runtime.getRuntime();
rt.exec("cmd.exe /c cd \""+"c:\\CombineImages\\"+"\" & start cmd.exe /k \"java -Xms1G -Xmx1G jar CombineImages.jar\"");
Put that code in your main method and replace with whatever command you want to run.
Upvotes: 1
Reputation: 6816
This should work
You need something like
String[] command =
{
"cmd",
};
Process p = Runtime.getRuntime().exec(command);
new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
stdin.println("dir c:\\ /A /Q");
// write any other commands you want here
stdin.close();
int returnCode = p.waitFor();
System.out.println("Return code = " + returnCode);
SyncPipe Class:
class SyncPipe implements Runnable
{
public SyncPipe(InputStream istrm, OutputStream ostrm) {
istrm_ = istrm;
ostrm_ = ostrm;
}
public void run() {
try
{
final byte[] buffer = new byte[1024];
for (int length = 0; (length = istrm_.read(buffer)) != -1; )
{
ostrm_.write(buffer, 0, length);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private final OutputStream ostrm_;
private final InputStream istrm_;
}
Upvotes: 1