如何在Java中将String读入InputStream?
我希望能够将String say = "say"
转换为InputStream / InputSource。我该怎么做?
答案 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();
}
}
答案 1 :(得分:2)
像...一样的东西。
InputStream is = new ByteArrayInputStream(sValue.getBytes());
应该工作......
答案 2 :(得分:0)
您可以使用ByteArrayInputStream
。它使用byte[]
方法从InputStream
读取元素。
答案 3 :(得分:0)
对于InputStream
,MadProgrammer有答案。
如果Reader
没问题,那么您可以使用:
Reader r = StringReader(say);