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!
Asked
Active
Viewed 2.9k times
18
3 Answers
26
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)

maerics
- 151,642
- 46
- 269
- 291
-
`return new ByteArrayInputStream(sb.toString().getBytes(StandardCharsets.UTF_8));` – Nov 12 '13 at 17:42
8
See if you can get the StringBuffer
to a byte[]
then use a ByteArrayInputStream.

gnat
- 6,213
- 108
- 53
- 73

James 'Cookie' Cook
- 556
- 2
- 12
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");
}
}

gtgaxiola
- 9,241
- 5
- 42
- 64

NameNotFoundException
- 876
- 14
- 31