How can I read from a BufferedReader in Java without blocking?

左心房为你撑大大i 提交于 2019-11-29 08:04:40

May be all you need is the InputStream without wrapping it in a BufferedReader

while (inputStream.available() > 0) {
     int i = inputStream.read(tmp, 0, 1024);
     if (i < 0)
          break;
     strBuff.append(new String(tmp, 0, i));
}

I hope this helps.

If you want to read responses asynchronously, I suggest starting a thread which read a BufferedReader. This is much simpler to code and easier to control.

I did something similar recently using a CountDownLatch. There may be some better ways, but this is pretty easy, and seems to work reasonably well. You can adjust the wait tome of the CountDownLatch to suit your needs.

package com.whatever;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestRead {
    private static final Logger log = LoggerFactory.getLogger(TestRead.class);
    private CountDownLatch latch = new CountDownLatch(1);

    public void read() {
        URLReader urlReader = new URLReader();
        Thread listener = new Thread(urlReader);
        listener.setDaemon(true);
        listener.start();
        boolean success = false;
        try {
            success = latch.await(20000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            log.error("error", e);
        }
        log.info("success: {}", success);
    }

    class URLReader implements Runnable {
        public void run() {
            log.info("run...");
            try {
                URL oracle = new URL("http://www.oracle.com/");
                URLConnection yc = oracle.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
                String inputLine;
                while ((inputLine = in.readLine()) != null)
                    System.out.println(inputLine);
                in.close();
                latch.countDown();
            } catch (Exception ex) {
                log.error("error", ex);
            }
            log.info("consumer is done");
        }

    }
    public static void main(String[] args) {
        TestRead testRead = new TestRead();
        testRead.read();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!