I am a longtime C++ programmer and I'm trying to understand how I would
phrase a common idiom in Java. Consider the following program in C++,
which reads tokens either from an istringstream (in memory) or from cin
(the console input):
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
void readTokensFromStream(istream &in) {
string s;
while(in >> s) {
cout << "read from token: '" << s << "'" << endl;
}
}
int main() {
istringstream fromMem("a man a plan a canal panama");
readTokensFromStream(fromMem);
readTokensFromStream(cin);
return 0;
}
I'd like to be able to write something similar in Java, but it doesn't
appear so easy there. Whereas in C++, both istringstream and cin are
istreams, in Java you have StringReader (a reader, not a stream) and
System.in (an InputStream, not a reader). Is there a way to find a
common interface or adapter between the stream and reader/writer worlds
so that the program above can be elegantly stated in Java? My
definition of elegant would involve abstracting out the difference so
that readTokensFromStream could continue to be a single non-overloaded
method.
Thanks in advance.
Jordan
John Harrison - 05 Nov 2005 16:13 GMT
> I am a longtime C++ programmer and I'm trying to understand how I would
> phrase a common idiom in Java. Consider the following program in C++,
[quoted text clipped - 39 lines]
> Thanks in advance.
> Jordan
An InputStream is for reading bytes, a Reader is for reading characters.
A Reader must know about character set and encoding issues whereas an
InputStream doesn't need to worry.
You can use InputStreamReader to convert an InputStream to a Reader (and
you must explicitly or implicitly supply a CharSet when you do this).
Since your readTokensFromStream function is concerned with reading
character information it should take a Reader as a parameter.
john
Roedy Green - 05 Nov 2005 16:20 GMT
>Is there a way to find a
>common interface or adapter between the stream and reader/writer worlds
>so that the program above can be elegantly stated in Java?
You use InputStreams for raw byte streams and Readers for streams of
encoded characters ( 8 or 16 bit ).
You can convert any InputStream to a Reader.
For sample code using the console as a Reader, see
http://mindprod.com/applets/fileio.html

Signature
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.