Neither can I understand how to do better, I decided to write here.

You need to make sure that the InputStream receives data in the background. Tobish if the data is there, it calculates them and waits further. Does not close !.

If there is no data, it just waits, if the data is there, it accepts it and waits further.

How to do this?

  • What exactly is the implementation of InputStream speech? In general, the contract is: if there is no data yet, but the context implies that they will be (open socket, for example) reading from the stream is blocked. If there is no data and it is never foreseen (the socket is closed, for example), then the stream will return -1, and it can no longer be used. - Nofate

1 answer 1

For example:

private static void asyncRead(InputStream inputStream) { new Thread() { @Override public void run() { try { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) System.out.println(line); } catch (IOException e) { e.printStackTrace(); } } }.start(); } 
  • Does while not get false after reader.readLine () becomes empty? and then this thread is closed. And I need the stream to not close, but to be constantly alive, until you have to let the team say off or the application closes - Andro
  • @xTIGRx all depends on what is the source of the inputStream. if this is a file, then of course the stream will reach the end of the file and end, if this is some kind of "infinite stream", for example reading from a socket, then the read operation will lock and wait for data to appear. - Artem Konovalov
  • Listen, why does the line have to get null? he will never get it. If the collapse of something does not happen - Andro
  • @xTIGRx is a fair comment, but I don’t know where you are trying to read the data from there. If this is a socket, then you must provide some kind of stop mechanism, for example, transfer some sequence of characters, which would result in the stream ending. - Artem Konovalov
  • Bluetooth socket. As long as there is a connection stream or loop to hold on and waiting for data, data comes again, waiting waits off. It should be so - Andro