Algorithm
- Create a method
convertInputStreamToString
that takes an InputStream as input. - Initialize a BufferedReader or Scanner to read the InputStream.
- Create a StringBuilder to store the content of the InputStream.
- Use a loop to iterate through each line or character in the InputStream.
- If using BufferedReader:
- Read each line using
readLine()
method until null is encountered. - Append each line to the StringBuilder.
- Read each line using
- If using Scanner:
- Use
next()
ornextLine()
methods to read tokens or lines. - Append each token or line to the StringBuilder.
- Use
- If using BufferedReader:
- Close the BufferedReader or Scanner to release resources.
- Convert the StringBuilder to a String using the
toString()
method. - Return the resulting String.
Code Examples
#1 Code Example- Java Program Convert InputStream to String
Code -
Java Programming
import java.io.*;
public class InputStreamString {
public static void main(String[] args) throws IOException {
InputStream stream = new ByteArrayInputStream("Hello there!".getBytes());
StringBuilder sb = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
System.out.println(sb);
}
}
Copy The Code &
Try With Live Editor
Output
Hello there!
Demonstration
Java Programing to Convert InputStream to String-DevsEnv