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