0

From a java application I run a bat file which starts another java application:

  ProcessBuilder processBuilder = new ProcessBuilder("path to bat file");
  Process process = processBuilder.start();

But the process never starts and no errors gets printed. But if I add the line:

  String resultString = convertStreamToString(process.getInputStream());

after : Process process = processBuilder.start();

where:

  public String convertStreamToString(InputStream is) throws IOException {
    /*
     * To convert the InputStream to String we use the Reader.read(char[]
     * buffer) method. We iterate until the Reader return -1 which means there's
     * no more data to read. We use the StringWriter class to produce the
     * string.
     */
    if (is != null) {
      Writer writer = new StringWriter();
      char[] buffer = new char[1024];
      try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
          writer.write(buffer, 0, n);
        }
      } finally {
        is.close();
      }
      return writer.toString();
    } else {
      return "";
    }   }

it runs fine! Any ideas?

u123
  • 15,603
  • 58
  • 186
  • 303

2 Answers2

0

If it's really a batch file, you should run the command line interpreter as process (e.g. cmd.exe) with that file as parameter.

mbx
  • 6,292
  • 6
  • 58
  • 91
  • Do you mean something like this:ProcessBuilder pb = new ProcessBuilder( "cmd", "/c", "mybat.bat", "param 1", "param 2", "param 3"); I have tried that but it gives the same result. – u123 Mar 18 '11 at 09:10
  • How did you check, that the process was (not) running, ProcessExplorer, Java Console? – mbx Mar 18 '11 at 10:19
0

Solved here:

Starting a process with inherited stdin/stdout/stderr in Java 6

But, FYI, the deal is that sub-processes have a limited output buffer so if you don't read from it they hang waiting to write more IO. Your example in the original post correctly resolves this by continuing to read from the process's output stream so it doesn't hang.

The linked-to article demonstrates one method of reading from the streams. Key take-away concept though is you've got to keep reading output/error from the subprocess to keep it from hanging due to I/O blocking.

Community
  • 1
  • 1
u123
  • 15,603
  • 58
  • 186
  • 303