In this tutorial, we will learn about the Java InputStreamReader, its constructors and its methods with the help of an example.
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly
Methods | Desciption |
---|---|
void close() | Closes the stream and releases any system resources associated with it. |
String getEncoding() | Returns the name of the character encoding being used by this stream. |
int read() | Reads a single character. |
int read(char[] cbuf, int offset, int length) | Reads characters into a portion of an array. |
boolean ready() | Tells whether this stream is ready to be read. |
Suppose we have a file named input.txt with the following content.
This file consists of a single line.
import java.io.InputStreamReader;
import java.io.FileInputStream;
class Codemistic
{
public static void main(String[] args)
{
// Creates an array of character
char[] array = new char[100];
try
{
// Creates a FileInputStream
FileInputStream file = new FileInputStream("input.txt");
// Creates an InputStreamReader
InputStreamReader input1 = new InputStreamReader(file);
// Reads characters from the file
input.read(array);
System.out.println("Data in the stream:");
System.out.println(array);
// Creates an InputStreamReader specifying the encoding
InputStreamReader input2 = new InputStreamReader(file, Charset.forName("UTF8"));
// Returns the character encoding of the input stream
System.out.println("Character encoding of input1: " + input1.getEncoding());
System.out.println("Character encoding of input2: " + input2.getEncoding());
// Closes the reader
input1.close();
input2.close();
}
catch(Exception e)
{
e.getStackTrace();
}
}
}
Output :
Data in the stream:
This file consists of a single line.
The character encoding of input1: Cp1252
The character encoding of input2: UTF8