Sai Sai
Sai Sai

Reputation: 115

while loop is not exiting when reading a file through BufferedReader

In my application I have client and server programms, whenever server got connection from client the server will send all the available id's from MySQL table to client, for this I have used while loop to read the contents of file.

I tried the following code:

while((a=in.read())!=-1)

but my problem when there is no contents in file to read the while loop is not exiting, it is stopping there itself. How to exit the while loop?

Upvotes: 0

Views: 452

Answers (2)

Bimalesh Jha
Bimalesh Jha

Reputation: 1504

in.read() will block till data is available to be read. Refer the API docs http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#read()

This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

You can do in.available() to check if any byte is available to read before doing in.read().

Upvotes: 1

asifsid88
asifsid88

Reputation: 4711

You should not be using the while loop, rather you should go with threads, which will wait for the input from the socket and when the data is available it will read and then it will send/ process the input found in the stream. Using while and waiting (blocking) your main thread is not a good idea

Upvotes: 0

Related Questions