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 @Deprecra
I know this is an old question but I had the same problem myself today, and this was my solution:
public static InputStream getStream(final CharSequence charSequence) {
return new InputStream() {
int index = 0;
int length = charSequence.length();
@Override public int read() throws IOException {
return index>=length ? -1 : charSequence.charAt(index++);
}
};
}
There is an adapter from Apache Commons-IO which adapts from Reader to InputStream, which is named ReaderInputStream.
Example code:
@Test
public void testReaderInputStream() throws IOException {
InputStream inputStream = new ReaderInputStream(new StringReader("largeString"), StandardCharsets.UTF_8);
Assert.assertEquals("largeString", IOUtils.toString(inputStream, StandardCharsets.UTF_8));
}
Reference: https://stackoverflow.com/a/27909221/5658642