简体   繁体   中英

Java: Open console programmatically and execute commands from it

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM