如何在Java中更改目录并执行文件

时间:2016-12-03 08:18:41

标签: java command-prompt

我必须在Java中执行Windows的以下 _.mergeWith(...input, _.add) 命令。

cmd命令:

cmd

执行结果

Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

//First i have to change my default directory//

C:\Users\shubh>D:

//Then move to a specific folder in the D drive.//

D:\>cd MapForceServer2017\bin\

//then execute the .mfx file from there.

D:\MapForceServer2017\bin>mapforceserver run C:\Users\shubh\Desktop\test1.mfx 

1 个答案:

答案 0 :(得分:0)

我有一些时间要求相同的要求,当时我从堆栈中得到了以下片段。试试这个。

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