Java - How to convert InputStream to Reader

Posted on November 10, 2016


An InputStreamReader class makes it possible to convert InputStream to Reader. It reads bytes and decodes them into characters.

Here is an example of InputStreamReader class.

InputStreamReaderExample.java

package com.boraji.tutorial.io;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

/**
 * @author imssbora
 */
public class InputStreamReaderExample {
	public static void main(String[] args) {
		String input = "This is an example of InputStreamReader";
		InputStream inputStream = null;
		Reader reader = null;
		try {
			inputStream = new ByteArrayInputStream(input.getBytes());
			// Conversion of InputStream to Reader
			reader = new InputStreamReader(inputStream, "UTF-8");

			int i;
			while ((i = reader.read()) != -1) {
				System.out.print((char) i);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

Output

This is an example of InputStreamReader