【发布时间】:2013-01-07 14:20:42
【问题描述】:
如何在 Java 中将字符串读入 InputStream?
我希望能够将String say = "say" 转换为 InputStream/InputSource。我该怎么做?
【问题讨论】:
-
如果你只是用谷歌搜索的话,这是非常有据可查的。
标签: java
如何在 Java 中将字符串读入 InputStream?
我希望能够将String say = "say" 转换为 InputStream/InputSource。我该怎么做?
【问题讨论】:
标签: java
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();
}
}
【讨论】:
str.getBytes() 中指定 Charset。
类似...
InputStream is = new ByteArrayInputStream(sValue.getBytes());
应该可以...
【讨论】:
您可以使用ByteArrayInputStream。它使用InputStream 方法从byte[] 中读取元素。
【讨论】:
对于InputStream MadProgrammer 有答案。
如果Reader 没问题,那么您可以使用:
Reader r = StringReader(say);
【讨论】: