InputStreamReader InputStreamReader(InputStream, String) in Java

InputStreamReader(InputStream, String): This method is available in the java.io.InputStreamReader class of Java.

Syntax:

java.io.InputStreamReader.InputStreamReader(InputStream in, String charsetName) throws UnsupportedEncodingException

This method takes two arguments. This method creates an InputStreamReader that uses the named charset.

Parameters: Two parameters are required for this method.

in: An InputStream.

charsetName: The name of a supported charset.

Throws:

UnsupportedEncodingException - If the named charset is not supported

Approach 1: When no exception

Java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class InputStreamReaderConstructor4 {
    public static void main(String[] args) throws IOException {

        File file = new File("D:\\hello.txt");
        InputStream in = new FileInputStream(file);
        String charsetName = "UTF-8";
        InputStreamReader inputStreamReader =
new InputStreamReader(in, charsetName);

        System.out.println(inputStreamReader);
        inputStreamReader.close();
    }
}

Output:

java.io.InputStreamReader@7637f22


Approach 2: UnsupportedEncodingException 

Java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class InputStreamReaderConstructor4 {
    public static void main(String[] args) throws IOException {

        File file = new File("D:\\hello.txt");
        InputStream in = new FileInputStream(file);
        String charsetName = "UTF-81919";
        InputStreamReader inputStreamReader =
new InputStreamReader(in, charsetName);

        System.out.println(inputStreamReader);
        inputStreamReader.close();
    }
}

Output:

Exception in thread "main" java.io.UnsupportedEncodingException: UTF-81919 at java.base/sun.nio.cs.StreamDecoder.forInputStreamReader(StreamDecoder.java:81) at java.base/java.io.InputStreamReader.<init>(InputStreamReader.java:96)


Some more methods of InputStreamReader

close(): This method closes the stream and releases any system resources associated with it.

InputStreamReader(InputStream): This method creates an InputStreamReader that uses the default charset.

InputStreamReader(InputStream, Charset): This method creates an InputStreamReader that uses the given charset.

InputStreamReader(InputStream, CharsetDecoder): This method creates an InputStreamReader that uses the given charset decoder. 

getEncoding(): This method returns the name of the character encoding being used by this stream.

read(): This method reads a single character.

read(char[], int, int): This method reads characters into a portion of an array.

ready(): This method tells whether this stream is ready to be read. 


No comments:

Post a Comment