如何在Java中将字符串读入inputStream?

3

5
如果你只是谷歌一下,这个问题已经有了很好的文献记录。 - Jordan Kaye
4个回答

4
public class StringToInputStreamExample {
    public static void main(String[] args) throws IOException {
    String str = "This is a String ~ GoGoGo";

    // convert String into InputStream
    InputStream is = new ByteArrayInputStream(str.getBytes());

    // read it with BufferedReader
    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }

    br.close();
   }
}

来源:Java中如何将字符串转换为InputStream


+1 很好的使用了 reader :) - MadProgrammer
3
如果在 str.getBytes() 中没有指定字符集,将返回 -1。请注意,在翻译过程中不要改变原文意思,只需使翻译更加通俗易懂。 - Louis Wasserman

2

类似于...

InputStream is = new ByteArrayInputStream(sValue.getBytes());

应该可以工作...


0
对于一个 InputStream,MadProgrammer 有答案。
如果可以使用 Reader,那么你可以使用:
Reader r = StringReader(say);

0
你可以使用ByteArrayInputStream。它使用InputStream方法从byte[]中读取元素。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接