javajava-meinputstreammidletstringbuffer

How to convert StringBuffer to InputStream in Java ME?


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!


Solution

  • 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)