It is always advisable to mention the character set while converting String to byte array using getBytes method. If the default character set of the platform you are using is ASCII, and if the String is encoded in UTF-8 encoding, characters will be lost during the conversion as given in below example.

1

2

3

4

5

6

7

8

Stringstr="Ã string çöntäining nön äsçii çhäräçters";

InputStream is=newByteArrayInputStream(str.getBytes());

BufferedReader br=newBufferedReader(newInputStreamReader(is));

Stringline=null;

while((line=br.readLine())!=null)

System.out.println(line);

Output

1

? string ??nt?ining n?n ?s?ii ?h?r??ters

As you can see, missing characters are displayed as question marks.

Convert String to InputStream using Apache Commons library

If you are using Apache Commons library, you can use toInputStream method of IOUtils class to convert String to InputStream.

About the author

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.