0

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

2 Answers 2

1

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.

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

1 Comment

This works for me to launch command window and execute command via opened command prompt.
1

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_;
}

1 Comment

This was a very useful answer thank you for posting it. The other answer worked for me but this is defiantly a good avenue to explore as well. Thanks again for taking the time to help.

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.