Search code examples
javawindowsprocessbuilder

ProcessBuilder to execute custom executable


Okay, I have tried a dozen different ways and no success. I want to execute a custom exe and grab the output. It runs fine from the command prompt. I get the "dir" to work fine, but not custom.exe. Here is the code:

  List<String> command = new ArrayList<String>();
  command.add("cmd");          // Even removed these two lines
  command.add("/c");           // aka hail mary coding.
  //command.add("dir");
  command.add("custom.exe");   // even tried "c://custom.exe"

  String line;
  Process p = new ProcessBuilder(command).start();
  BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
  while ((line = input.readLine()) != null) {
    System.out.println(line);
  }

I get no output at all. If I place it in a batch file, i get output. I have a feeling it has something to do with %PATH%. Back at it...

EDIT--> So turns out that the output from this custom exe goes to error, so to see what is happening i have the code:

  List<String> command = new ArrayList<String>();
  command.add(System.getenv("ProgramFiles(x86)") + "\\mydir\\custom.exe";

  String line;
  ProcessBuilder pb = new ProcessBuilder(command);
  pb.redirectErrorStream(true);
  Process p = pb.start();
  BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
  while ((line = input.readLine()) != null) {
    System.out.println(line);
  }

And it works like a hot damn. :)


Solution

  • You don't need the lines

    command.add("cmd");
    command.add("/c");
    

    That would only be required for a batch file. I would rather specify the full path to the executable.

    Maybe the output is on stderr? Try replacing p.getInputStream() with p.getErrorStream().