In this tutorial, we will see “How to convert InputStream to Reader in Java ?” An InputStreamReader class helps to convert InputStream to Reader. Here, we are going to use 2 different approaches to achieve this.
Convert InputStream to Reader in Java with example...!!! Share on X
Approach 1.
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class InputStreamReaderApproach1 {
public static void main(String[] args) {
String inputStringObj = "This is Techndeck, a Unique place for Programmers.";
InputStream inputStreamObj = null;
Reader readerObj = null;
try {
inputStreamObj = new ByteArrayInputStream(inputStringObj.getBytes());
readerObj = new InputStreamReader(inputStreamObj, "UTF-8");
int i;
while ((i = readerObj.read()) != -1) {
System.out.print((char) i);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Output:
This is Techndeck, a Unique place for Programmers.
Approach 2.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
public class InputStreamReaderApproach2 {
public static void main(String[] args) {
File fileObj = new File("/Users/d33p4k/Documents/Techndeck/JavaPractice/InputString"); //InputString is a .txt file //This is Mac based path, if you are using Windows or Linus, Choose accordingly.
InputStream inputStreamObj = null;
BufferedReader bufferedReaderObj = null;
String lineObj = null;
try {
inputStreamObj = new FileInputStream(fileObj);
bufferedReaderObj = new BufferedReader(new InputStreamReader(inputStreamObj));
while (bufferedReaderObj.ready()) {
lineObj = bufferedReaderObj.readLine();
System.out.println(lineObj);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Output:
Hi, How are you? This is Techndeck, a Unique place for Programmers. I hope you will like the content of this website.
Do you like this Post? – then check my other helpful posts: