shawn
shawn

Reputation: 4223

Can I use both Scanner which uses an InputStream and the inputstream itself at the same in the same program?

I suppose this is the input counterpart of this question which I asked some time back:

Can I use both PrintWriter and BufferedOutputStream on the same outputstream?

Q1) I need to read both String lines and byte [] from the same inputstream. So can I use the scanner wrapper to read lines first and then use the inputstream directly to read byte []? Will it cause any conflict?

Q2) If there are no more references to the scanner object and it gets garbage collected, will it automatically close the connection?

Q3) If the answer to the first question is yes and the answer to the second question is no, once I am done with the reading I only have to call inputstream.close() and not Scanner right? (Because by then I won't have a handle to the scanner object anymore)

Upvotes: 3

Views: 808

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533670

Q1) Yes, the scanner buffers its input so when you come to switch to a different stream some of the bytes you want may have been consumed.

If you can use the Scanner to read bytes, that is a better option.

Q2) The connection will be closed when it is cleaned up.

Q3) You only need to close the input stream as Scanner is a pure Java object (and an input) For Buffered outputs you need to call flush() or close() to ensure unwritten data is sent.

Upvotes: 1

Sanjay T. Sharma
Sanjay T. Sharma

Reputation: 23218

For 1), you can always read bytes and convert them to String using the encoding of your choice. I'm pretty sure this is what all "readers" to under the hood.

For 2), no, Scanner class doesn't override the finalize method so I'm pretty sure it doesn't close the handle (and it really shouldn't). The section on finalizers in the Effective Java book has a detailed explanation on this topic.

For 3), closing the Scanner would automatically close the underlying stream. I'm pretty sure this is how almost all I/O classes handle the passed in file/resource handle.

Upvotes: 1

Related Questions