17

我是 Java 新手,正在学习 Java ME 开发。我陷入了这种转换。请帮我转换StringBufferInputStream. 谢谢!

4

3 回答 3

25

见课ByteArrayInputStream。例如:

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

请注意,您可能希望在该getBytes()方法上使用显式字符编码,例如:

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

(感谢@g33kz0r)

于 2011-11-10T14:26:02.570 回答
8

看看你是否可以得到StringBuffer一个byte[]然后使用ByteArrayInputStream

于 2011-11-10T14:24:28.467 回答
2

这是我在Java 示例中找到的最佳答案

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");
        }
}
于 2014-04-24T05:55:30.083 回答