BufferedReader seems to infinitely read the first line

987 views Asked by At

I'm trying to run Handbrake through a Java app I'm writing, and am having trouble waiting for Handbrake to finish.

When I try this :

        ProcessBuilder builder = new ProcessBuilder(
                "cmd.exe", "/c", command);
        Process p = builder.start();

        BufferedReader inputreader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = null;
        while((line = inputreader.readLine()) != null)
        {
            System.out.println(line);
        }

The output I get is :

Encoding: task 1 of 1, 0.00 %

Over and over, and the file never gets converted.

When I change it to the following:

        BufferedReader inputreader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader errorreader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        String line = null;
        String line2 = null;
        while((line = inputreader.readLine()) != null && (line2 = errorreader.readLine()) != null)
        {
            System.out.println(line);
            System.out.println(line2);
        }

It works on my test files, however it gets hung-up when the errorreader runs out of lines to read and the readLine() locks the thread infinitely. On full length files the file gets converted but this portion of code gets locked so it never continues with the application.

Any suggestions?

1

There are 1 answers

3
Erwin Bolwidt On BEST ANSWER

Call builder.redirectErrorStream(true); before creating the process (this will merge the input and the error stream into one: the input stream), and only read from the InputStream.

That should solve the problem of the error stream running out of data before the input stream.

If you do want to keep them separate, then you can start two threads, on to read from the input stream and one from the error stream.