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.

2
  • 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... Commented May 26, 2015 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. Commented May 26, 2015 at 21:10

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You're right. Is the documentation claiming that this feature is supported even though it really isn't?
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. :-(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.