[jdom-interest] StringReader versus StringBufferInputStream

Tatu Saloranta cowtowncoder at yahoo.com
Sun Aug 29 20:40:39 PDT 2004


--- David Wall <d.wall at computer.org> wrote:

> The SAXBuilder.build() javadocs say this about using
> a StringReader (Reader
> actually):  "It's always safer to use an InputStream
> rather than a Reader,
> if it's available."

This seems wrong. I think what it should say is "if
you have a stream and are not sure about its encoding,
it's safer to pass stream instead of trying to create
a reader". This because XML parsers in general can
auto-detect encoding from initial stream bytes, and/or
from xml declaration (if one exists), and then
construct appropriate reader that uses proper decoder.
But properly constructed Readers are as safe as it
gets, that statement just seems weird.

> But if I already have the XML in a String, I could
> use
> java.io.StringBufferInputStream, though that's been
> deprecated for
> StringReader because:  "Deprecated. This class does
> not properly convert
> characters into bytes. As of JDK 1.1, the preferred
> way to create a stream
> from a string is via the StringReader class.  ...   
> Only the low eight bits
> of each character in the string are used by this
> class.".

This is same as assuming contents are valid ISO-Latin
(ISO-8859-1), and thus only works with european
languages... and that's why it's deprecated. But you
really wouldn't benefit using it, because:
 
> So the question is, why is it "safer" to use an
> InputStream since the
> StringBufferInputStream is deprecated?  Would you
> recommend using a
> StringReader or converting the String to a byte
> array and then using
> ByteArrayInputStream for the SAXBuilder.build()?  Or
> something else
> entirely?

I'm pretty sure that if you have your content as a
String already, StringReader is the optimal choice.
You do not need any char encoding/decoding; if you did
create a stream, that first encode characters into
bytes, then xml stream reader would decode characters
from those bytes. Further, StringReader is as
efficient as it gets, for reading stuff from Strings
using Reader interface.

-+ Tatu +-

> 
> Thanks,
> David
> 
> _______________________________________________
> To control your jdom-interest membership:
>
http://www.jdom.org/mailman/options/jdom-interest/youraddr@yourhost.com
> 



		
__________________________________
Do you Yahoo!?
Yahoo! Mail - 50x more storage than other providers!
http://promotions.yahoo.com/new_mail


More information about the jdom-interest mailing list