InputStreamReader Class

Java InputStreamReader tutorial The InputStreamReader class reads characters from a byte input stream. It reads bytes and decodes them into characters using a specified charset. The decoding layer transforms bytes to chars according to an encoding standard . There are many available encodings to choose from.

InputStreamReader class performs two tasks:

  1. Read input stream of keyboard.
  2. Convert byte streams to character streams.

The following Java program obtain an InputStreamReader from keyboard

import java.util.*; import java.io.*; public class TestClass{ public static void main( String[] args ){ try { InputStreamReader isReader = new InputStreamReader(System.in); BufferedReader bReader=new BufferedReader(isReader); System.out.println("Enter anything......"); String data=bReader.readLine(); System.out.println("You Entered.... "+data); } catch (IOException e) { e.printStackTrace(); } } }

The following Java program obtain an InputStreamReader from a file

import java.util.*; import java.io.*; public class TestClass{ public static void main( String[] args ){ try { InputStream is = new FileInputStream("d:\\test.txt"); Reader isr = new InputStreamReader(is); int data = isr.read(); while(data != -1){ data = isr.read(); char chr = (char) data; System.out.print(chr); } isr.close(); } catch (IOException e) { e.printStackTrace(); } } }

How do I convert a String to an InputStream in Java?

ByteArrayInputStream does the trick from Java 1.4

InputStream is = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8));
From Java 1.7, StandardCharsets defines constants for Charset including UTF-8 . You should include import java.nio.charset.StandardCharsets; in your Java file. Note that this assumes that you want an InputStream that is a stream of bytes that represent your original string encoded as UTF-8 .

The following Java program read a String as InputStream.

import java.util.*; import java.io.*; import java.nio.charset.StandardCharsets; public class TestClass{ public static void main( String[] args ){ try { String inputString = "This is a test !! "; InputStream is = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8)); Reader isr = new InputStreamReader(is); int data = isr.read(); while(data != -1){ data = isr.read(); char chr = (char) data; System.out.print(chr); } isr.close(); } catch (IOException e) { e.printStackTrace(); } } }