【问题标题】:How can I read a String into an inputStream in Java? [duplicate]如何在 Java 中将字符串读入 inputStream? [复制]
【发布时间】:2013-01-07 14:20:42
【问题描述】:

可能重复:
How do I convert a String to an InputStream in Java?

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

我希望能够将String say = "say" 转换为 InputStream/InputSource。我该怎么做?

【问题讨论】:

  • 如果你只是用谷歌搜索的话,这是非常有据可查的。

标签: java


【解决方案1】:
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();
   }
}

来源:How To Convert String To InputStream In Java

【讨论】:

  • +1 很好地使用了阅读器 :)
  • -1 表示未在 str.getBytes() 中指定 Charset
【解决方案2】:

类似...

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

应该可以...

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      对于InputStream MadProgrammer 有答案。

      如果Reader 没问题,那么您可以使用:

      Reader r = StringReader(say);
      

      【讨论】:

        猜你喜欢
        • 2010-09-23
        • 2017-01-22
        • 2010-12-18
        • 2010-10-21
        相关资源
        最近更新 更多