如何在Java中将String读入inputStream?

时间:2013-01-23 22:59:28

标签: java

  

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

如何在Java中将String读入InputStream?

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

4 个答案:

答案 0 :(得分: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();
   }
}

来源:How To Convert String To InputStream In Java

答案 1 :(得分:2)

像...一样的东西。

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

应该工作......

答案 2 :(得分:0)

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

答案 3 :(得分:0)

对于InputStream,MadProgrammer有答案。

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

Reader r = StringReader(say);