- Given inputStream in Java
- Convert InputStream to String using InputStreamReader class in java.
Methods of InputStreamReader used for inputStream to String conversion
Method Name |
Description |
InputStreamReader(InputStream in,Charset cs) |
Creates an InputStreamReader that uses the given charset. |
int read(char[] cbuf, int offset, int length) |
Reads characters into a portion of an array |
Algorithm: convert InputStream to String in java
- Create inputSteam from dummy String.
- Create StringBuilder instance to store stream buffer
- Read input stream till reach end of file
- Append the read buffer to StringBuilder
- Convert StringBuilder to String
- Print the output String.
Code: convert InputStream to String – InputStreamReader java
package org.learn;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
public class InputStreamToString {
public static void main(String[] args) throws IOException {
InputStream inputStream = getInputStream();
char[] buffer = new char[1024];
StringBuilder builder = new StringBuilder();
try(Reader in = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
int ch;
while ((ch = in.read(buffer, 0, buffer.length)) > 0) {
builder.append(buffer, 0, ch);
}
}
System.out.println("InputStream to String output is:");
System.out.println(builder.toString());
}
private static InputStream getInputStream () {
String dummyString = "Java.io.InputStream class is the superclass of \r\n" +
"all classes representing an input stream of bytes.";
return new ByteArrayInputStream(dummyString.getBytes());
}
}
Output: convert InputStream to String in Java
InputStream to String output is:
Java.io.InputStream class is the superclass of
all classes representing an input stream of bytes.