Description

On this document we will be showing a java example on how to use the getEncoding() method of InputStreamReader Class. This method returns the name of the character encoding being used by this stream.

If the encoding has an 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. This method will return null if the stream has been closed.

Method Syntax

public String getEncoding()

Method Argument

Data Type Parameter Description
N/A N/A N/A

Method Returns

This method return a String, which denotes the historical name of this encoding, or null if the stream has been closed.

Compatibility

Requires Java 1.2 and up

Java InputStreamReader getEncoding() Example

Below is a java code demonstrates the use of getEncoding() method of InputStreamReader class. The example presented might be simple however it shows the behaviour of the getEncoding() method of InputStreamReader class.

package com.javatutorialhq.java.examples;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

/*
 * This example source code demonstrates the use of  
 * getEncoding() method of InputStreamReader class
 */

public class InputStreamReaderGetEncodingExample {

	public static void main(String[] args) {		
		
		try {
			// initialize an input stream which in this case
			// we are intended to read a file thus 
			// FileInputStream object suits it best
			FileInputStream fis = new FileInputStream("C:javatutorialhq"
					+ "inputtest_file.txt");
			
			// initialize InputStreamReader object
			InputStreamReader is = new InputStreamReader(fis);
			
			// get the character encoding used by this stream
			String encoding = is.getEncoding();
			
			// print the result
			System.out.println("Current Encoding:"+encoding);
			
			// close the stream
			is.close();
		} catch (FileNotFoundException e) {
			System.out.println("File does not exists");
		} catch (IOException e) {
			System.out.println("IOException occured");
		}		
		

	}

}

Sample Output

Below is the sample output when you run the above example.

java lang InputStreamReader getEncoding() example output