Algorithm


  1. Create a method convertInputStreamToString that takes an InputStream as input.
  2. Initialize a BufferedReader or Scanner to read the InputStream.
  3. Create a StringBuilder to store the content of the InputStream.
  4. 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.
    • If using Scanner:
      • Use next() or nextLine() methods to read tokens or lines.
      • Append each token or line to the StringBuilder.
  5. Close the BufferedReader or Scanner to release resources.
  6. Convert the StringBuilder to a String using the toString() method.
  7. 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

x
+
cmd
Hello there!
Advertisements

Demonstration


Java Programing  to Convert InputStream to String-DevsEnv