How to convert String to InputStream in Java

Here is the example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.yuxifan
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class String2InputstreamExample {
public static void main(String[] args) throws IOException {
String s = "Just a test";
// First, convert string to InputStream
InputStream is = new ByteArrayInputStream(s.getBytes());
// Use BufferedReader to read it
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// Output it
String currentLine;
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine);
}
br.close();
}
}
Share