How to determine the exact state of a BufferedReader?

后端 未结 8 1498
慢半拍i
慢半拍i 2020-12-17 00:21

I have a BufferedReader (generated by new BufferedReader(new InputStreamReader(process.getInputStream()))). I\'m quite new to the concept of a

相关标签:
8条回答
  • 2020-12-17 00:56

    This is a pretty fundamental issue with java's blocking I/O API.

    I suspect you're going to want to pick one of:

    (1) Re-visit the idea of using threading. This doesn't have to be complicated, done properly, and it would let your code escape a blocked I/O read fairly gracefully, for example:

    final BufferedReader reader = ...
    ExecutorService executor = // create an executor here, using the Executors factory class.
    Callable<String> task = new Callable<String> {
       public String call() throws IOException {
          return reader.readLine();
       }
    };
    Future<String> futureResult = executor.submit(task);
    String line = futureResult.get(timeout);  // throws a TimeoutException if the read doesn't return in time
    

    (2) Use java.nio instead of java.io. This is a more complicated API, but it has non-blocking semantics.

    0 讨论(0)
  • 2020-12-17 00:57

    Have you confirmed by experiment your assertion that ready() will return false even if the underlying stream is at end of file? Because I would not expect that assertion to be correct (although I haven't done the experiment).

    0 讨论(0)
提交回复
热议问题