Yesterday I lamented that far too many Java APIs put useful data into a stream but fail to offer me an accessor method to obtain the data as a String. Today I know how to get that data as a String.
The secret is the ByteArrayOutputStream class. You "print" to this stream, then call toString() on it to get the String. Or you can call toByteArray() if you need that for some reason.
This looks like a painful extra step to my normal way of thinking, but I can see that a case might somehow be made that it is more flexible design, since the mechanism exists to take any method that outputs to streams and obtain the data in a String. I guess having methods that are inappropriately coupled to streams seems convenient when it's so inconvenient to access streams.
All I wanted to do yesterday was send the little chunk of XML I'd manipulated to log4j so I could see it in a test run and make sure it was right without having to write it to a file and go open the file to look at it. I think logging is a perfect example of why there ought to be accessors like this for every piece of data, rather than methods that force you to output.
Minimize side effects!
Not Quite Right (Score:2)
The problem with doing things like this is that you are completely ignoring the encoding. Encoding is one of the reason why there are parallel IO hierarchies in Java: InputStream [sun.com]/OutputStream [sun.com] vs Reader [sun.com]/Writer [sun.com]. The latter understand characters, the former understand bytes. Unfortunately, every time you go near a Reader/Writer, you need to specify a character encoding. As a rule, I try to prefer Reader/Writer where I can.
Classes to look at:
Re: (Score:2)
Re: (Score:2)
Thanks for the pointer!
J. David works really hard, has a passion for writing good software, and knows many of the world's best Perl programmers
Re: (Score:2)
Thank you for the useful information!
For the record, ByteArrayOutputStream.toString() does offer a version which specifies the character encoding as a parameter. But that's definitely something I wasn't thinking about (especially since I just wanted it for logging). My personal wiring is probably far too close to Paul Graham's recent unforgivable sin in making Arc ASCII-only for the taste of people around here, or anyone steeped in Java. It's something I'd prefer to leave as Somebody Else's Problem as
J. David works really hard, has a passion for writing good software, and knows many of the world's best Perl programmers
Re: (Score:2)
Reminds me of… (Score:1)
…Scheme:
Ordinary morality is for ordinary people. -- Aleister Crowley
Re:Reminds me of… (Score:2)
Or IO::Scalar in Perl. :)
J. David works really hard, has a passion for writing good software, and knows many of the world's best Perl programmers
Re: (Score:2)
Re: (Score:2)
Cool! Thank you!
J. David works really hard, has a passion for writing good software, and knows many of the world's best Perl programmers