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...!!! Click To Tweet
Approach 1.
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 | 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(); } } } |
1 | This is Techndeck, a Unique place for Programmers. |
Approach 2.
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 | 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(); } } } |
1 2 3 | Hi, How are you? This is Techndeck, a Unique place for Programmers. I hope you will like the content of this website. |