How do I convert a String to an InputStream in Java?

This question already has an answer here:

  • How do I turn a String into a InputStreamReader in java? 6 answers

  • Like this:

    InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));
    

    Note that this assumes that you want an InputStream that is a stream of bytes that represent your original string encoded as UTF-8.

    For versions of Java less than 7, replace StandardCharsets.UTF_8 with "UTF-8" .


    I find that using Apache Commons IO makes my life much easier.

    String source = "This is the source of my input stream";
    InputStream in = IOUtils.toInputStream(source, "UTF-8");
    

    You may find that the library also offer many other shortcuts to commonly done tasks that you may be able to use in your project.


    您可以使用StringReader并将阅读器转换为使用此另一个计算器上的解决方案的输入流。

    链接地址: http://www.djcxy.com/p/2210.html

    上一篇: 我在哪些情况下使用malloc vs new?

    下一篇: 如何在Java中将字符串转换为InputStream?