4

As has been answered repeatedly, you can easily convert a String to an InputStream.

When browsing the Java 8 documentation I came across the long-deprecated StringBufferInputStream class, which states that

As of JDK 1.1, the preferred way to create a stream from a string is via the StringReader class.

What is way is this referring to? There are several methods requiring classes in non-default libraries such as the error-prone ReaderInputStream from Apache Commons IO, but I'm looking for the preferred way mentioned in the documentation. The solutions referenced in other questions are sufficient for my use cases, but I'd still like to know what the documentation is referencing.

Update

Apparently this is a 16 year old bug that hasn't been fixed. The proposed solution in the link is to use the deprecated class. I can't imagine that is what is intended from what the documentation says.

Community
  • 1
  • 1
Will Beason
  • 3,417
  • 2
  • 28
  • 46
  • 4
    You need to understand the difference between a `byte` source and a `char` source and the amazing complexity of converting one to the other. The `Reader` API is designed to solve many issues that arise. `ReaderInputStream` is somewhat bugger and errorprone... – Boris the Spider May 26 '15 at 20:46
  • 1
    This isn't unique to Java 8. As you note, the class is long deprecated, and this message has existed since JDK 1.1. I would not give much credence to recommendations in deprecated documentation. – dimo414 May 26 '15 at 21:10

1 Answers1

2

I don't know the answer to the javadoc part, but the first answer you pointed to is a reasonable one: just use String.getBytes(encoding) to get byte array, then use ByteArrayInputStream.

But usually the more important question is this: why on earth do you NEED such conversion? In a well designed system, you should never need to go in this direction: it is against the normal flow of things where within JDK you deal with chars and Strings, and outside with bytes and Streams. So conversions in this direction are quite rare and it does not seem necessary for JDK to have explicit support.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • You're right. Is the documentation claiming that this feature is supported even though it really isn't? – Will Beason May 26 '15 at 21:04
  • 1
    To me it does sound like a leftover comment that should just be eliminated. I can't think of what it would otherwise refer to. :-( – StaxMan May 27 '15 at 21:38