InputStreamReader getEncoding() in Java

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

Syntax:

String java.io.InputStreamReader.getEncoding()

This method returns the name of the character encoding being used by this stream.

If the encoding has a historical name then that name is returned; otherwise, the encoding's canonical name is returned.

If this instance was created with the InputStreamReader(InputStream, String) constructor then the returned name, being unique for the encoding, may differ from the name passed to the constructor.

Note:

This method will return null if the stream has been closed.

Parameters: NA

Returns: The historical name of this encoding, or null if the stream has been closed.

Exceptions: NA

Approach 1: When the stream is not closed.

Java

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

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

        File file = new File("D:\\hello.txt");
        InputStream in = new FileInputStream(file);
        InputStreamReader inputStreamReader =
new InputStreamReader(in);

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

Output:

Cp1252


Approach 2: When the stream is closed

Java

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

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

        File file = new File("D:\\hello.txt");
        InputStream in = new FileInputStream(file);
        InputStreamReader inputStreamReader =
new InputStreamReader(in);

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

    }
}

Output:

null


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.

InputStreamReader(InputStream, String)This method creates an InputStreamReader that uses the named charset.

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