简体   繁体   中英

Closing BufferedReader without closing wrapped stream

I'm currently writing a program that communicates with a server using TCP sockets. Part of that requires sending information back and forth through several methods. However, I do not want to open up a new socket connection for each request, but I can't guarantee the number or the order of the requests. In order to handle this, I simply keep one socket instance that gets reused a lot.

However, in order to read the data I use BufferedReader wrapper classes. Because I reuse the same socket, I can't call close() on the reader, or I'll close the socket stream as well.

Do I need to call close() on the BufferedReader if I don't want to close the underlying stream? Will I cause a memory leak by not doing this? If I do need to call close() how can I return the memory without closing the socket's stream?

Note: I will close the underlying stream at program termination, this question isn't about that.

Don't close the BufferedReade . More important , don't discard the BufferedReader ; instead, pass it around rather than the SocketInputStream .

A BufferedReader , as its name implies, has an internal buffer. When you read from it, it tries to fill that buffer from the underlying Reader . Which means that, if you discard it, those bytes are gone.

And now some unasked advice:

  • Do you really want to use a Reader ? Most communication protocols are better implemented using a DataInputStream / DataOutputStream . With a Reader you're limited to character data (and in the case of BR , lines of character data).
  • Are you paying attention to encoding? The correct way to construct a Reader on top of an InputStream is to use the two-argument variant of InputStreamReader : new InputStreamReader(in, "UTF-8") (you can use an encoding other than UTF-8, but have a good reason ).
  • It's generally better to use a BufferedInputStream rather than a BufferedReader , because the translation from stream to reader may involve multiple reads. If you want readLine() , you can always use both.
  • Be sure to close the socket in either a finally or try-with-resources. See this for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM