How to convert StringBuffer to InputStream in Java ME?
Asked Answered
M

3

18

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!

Miser answered 10/11, 2011 at 14:19 Comment(0)
N
28

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)

Nash answered 10/11, 2011 at 14:26 Comment(1)
return new ByteArrayInputStream(sb.toString().getBytes(StandardCharsets.UTF_8));Contrived
I
8

See if you can get the StringBuffer to a byte[] then use a ByteArrayInputStream.

Iceberg answered 10/11, 2011 at 14:24 Comment(0)
D
2

This is the best answer I found on Java Examples

import java.io.ByteArrayInputStream;
import java.io.InputStream;
public class StringBufferToInputStreamExample {
        public static void main(String args[]){
                //create StringBuffer object
                StringBuffer sbf = new StringBuffer("StringBuffer to InputStream Example");
                /*
                 * To convert StringBuffer to InputStream in Java, first get bytes
                 * from StringBuffer after converting it into String object.
                 */
                byte[] bytes = sbf.toString().getBytes();
                /*
                 * Get ByteArrayInputStream from byte array.
                 */
                InputStream inputStream = new ByteArrayInputStream(bytes);
                System.out.println("StringBuffer converted to InputStream");
        }
}
Drugi answered 24/4, 2014 at 5:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.