I have a String
that I want to use as an InputStream
. In Java 1.0, you could use java.io.StringBufferInputStream
, but that has been @Deprecrated
(with good reason--you cannot specify the character set encoding):
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.
You can create a java.io.Reader
with java.io.StringReader
, but there are no adapters to take a Reader
and create an InputStream
.
I found an ancient bug asking for a suitable replacement, but no such thing exists--as far as I can tell.
The oft-suggested workaround is to use java.lang.String.getBytes()
as input to java.io.ByteArrayInputStream
:
public InputStream createInputStream(String s, String charset) throws java.io.UnsupportedEncodingException { return new ByteArrayInputStream(s.getBytes(charset)); }
but that means materializing the entire String
in memory as an array of bytes, and defeats the purpose of a stream. In most cases this is not a big deal, but I was looking for something that would preserve the intent of a stream--that as little of the data as possible is (re)materialized in memory.
We can convert a String to an InputStream object by using the ByteArrayInputStream class. The ByteArrayInputStream is a subclass present in InputStream class. In ByteArrayInputStream there is an internal buffer present that contains bytes that reads from the stream.
To convert an InputStream Object int to a String using this method. Instantiate the Scanner class by passing your InputStream object as parameter. Read each line from this Scanner using the nextLine() method and append it to a StringBuffer object. Finally convert the StringBuffer to String using the toString() method.
Java InputStream read InputStream reads bytes with the following read methods : read(byte[] b) — reads up to b. length bytes of data from this input stream into an array of bytes. read(byte[] b, int off, int len) — reads up to len bytes of data from this input stream into an array of bytes.
The input stream is linked with the file input.InputStream input = new FileInputStream("input. txt");
Update: This answer is precisely what the OP doesn't want. Please read the other answers.
For those cases when we don't care about the data being re-materialized in memory, please use:
new ByteArrayInputStream(str.getBytes("UTF-8"))
If you don't mind a dependency on the commons-io package, then you could use the IOUtils.toInputStream(String text) method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With