Convert a String to an InputStream in Java

This code example shows how to convert a String to an InputStream. This is sometimes necessary when calling different api:s that require a InputStream object as parameter but the value you need to pass is stored in a String object. To convert the parameter ‘name’ in the example below to an InputStream we create a ByteArrayInputStream object which takes a byte array as parameter, so we simply call getBytes on the String we want to convert. To make sure it is in the proper format we also provide the character set UTF-8 to the getBytes method which we supply using a constant from the StandardCharsets class.
Finally to make sure it has succeeded we print out every byte (character) in the stream on a separate row. Since the read-method of the inputstream returns an int, which is the decimal value of the byte, we convert the int value to a char before we print it out.

The output from the code above will be:

Search for more Java info on this site here:
Custom Search

Please type any questions here.