How to convert StringBuffer to InputStream in Java ME?

masiboo picture masiboo · Nov 10, 2011 · Viewed 24.3k times · Source

I'm new in Java and learning Java ME development. I got stuck in this conversion. Please help me to convert StringBuffer to InputStream. Thanks!

Answer

maerics picture maerics · Nov 10, 2011

See the class ByteArrayInputStream. For example:

public static InputStream fromStringBuffer(StringBuffer buf) {
  return new ByteArrayInputStream(buf.toString().getBytes());
}

Note that you might want to use an explicit character encoding on the getBytes() method, e.g.:

return new ByteArrayInputStream(buf.toString().getBytes(StandardCharsets.UTF_8));

(Thanks @g33kz0r)