简体   繁体   中英

How to run a .exe file through the command prompt in a Java program?

I've read other questions about running .exe files through command prompt but the answers given did not work for me--I tried several. I am generating input files for this .exe and I need to run them and get the output.

The command is this: C:\\exeDir\\myExe.exe -b C:\\inDir\\in.txt C:\\outDir\\out.txt

I have tried:

Process process = new ProcessBuilder("C:\\exeDir\\myExe.exe",
"-b C:\\inDir\\in.txt",
"C:\\outDir\\out.txt").start();

And

String[] cmd = { "C:\\exeDir\\myExe.exe",
 "-b C:\\inDir\\in.txt",
 "C:\\outDir\\out.txt" };
     Process p = Runtime.getRuntime().exec(cmd);
     p.waitFor();

As well as a few other variations. None have worked. What is the proper way for me to handle this? Thanks.

You're on the right track,

try {
  Process process = new ProcessBuilder(
      "C:\\exeDir\\myExe.exe",
      "-b", "C:\\inDir\\in.txt",
      "C:\\outDir\\out.txt").start();
  // to get the result...
  InputStream is = process.getInputStream();
  BufferedReader br = new BufferedReader(
      new InputStreamReader(is));
  String line;
  while ((line = br.readLine()) != null) {
    System.out.println(line);
  }
  process.waitFor();
  // Process finished.
} catch (Exception e) {
  // print any errors.
  e.printStackTrace();
}

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