Friday, February 11, 2011

BufferedReader.readLine() hangs

I debugged a simple program to learn JavaCompiler in new JDK, but found BufferedReader.readLine() hangs for some reason. BufferedReader.readLine() returns null toindicate that you have reached the end of the data stream (i.e. the remote has closed). At all other times, readLine() will block until there is a complete
line (i.e. a message terminated by a newline). If you need to know that there is data before attempting to read, try to use BufferedReader.isReady() method.

Here is the sample code:
        Runtime run = Runtime.getRuntime();
        Process p = run.exec("java");

        BufferedInputStream in = new BufferedInputStream(p.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
       
        if (br.ready()) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }

No comments:

Post a Comment