Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

InputStreamReader getEncoding() Method in Java

In this tutorial, we will learn about the getEncoding() method of the InputStreamReader class in Java. This method provides the name of the character encoding used by the current stream. If the stream is using a historical encoding name, it will return that, otherwise, it will return the canonical encoding name of the stream.

Syntax

Below is the syntax declaration of this method. It does not accept any parameter and it returns the encoding, historical or canonical, the name used by the stream, or simply null if the stream is closed.

public String getEncoding()

Example 1: Encode InputStreamReader in Java

In this example, we are learning about the getEncoding() method of InputStreamReader class. This method will return the character encoding of a given InputStreamReader. I the encoding is not explicitly mentioned in that case It will return a default encoding. In this example, we set the encoding as UTF8 and we can see it in the output

package studytonight;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
public class StudyTonight 
{
	public static void main(String args[])
	{
		try{  
			FileInputStream file = new FileInputStream("E:\\studytonight\\output.txt");  
			InputStreamReader reader = new InputStreamReader(file, Charset.forName("UTF8"));  			
			System.out.println("Character Encoding of the reader is: "+reader.getEncoding());
		}
		catch (Exception e)	{  
			System.out.print("Error: "+e.toString());
		}  
	}
}

Character Encoding of the reader is: UTF8

Example 2: Encode InputStreamReader in Java

.If we do not set the encoding to the stream then this method will return the default one, here in this example we didn't set any encoding but it returned Cp1252 because it was assigned to the stream by default.

import java.io.FileInputStream;
import java.io.InputStreamReader;
public class StudyTonight 
{
	public static void main(String args[])
	{
		try
		{  
			FileInputStream file = new FileInputStream("E:\\studytonight\\output.txt");  
			InputStreamReader reader = new InputStreamReader(file);  			
			System.out.println("Character Encoding of the reader is: "+reader.getEncoding());
		}
		catch (Exception e)	
		{  
			System.out.print("Error: "+e.toString());
		}  
	}
}


Character Encoding of the reader is: Cp1252

Conclusion

In this tutorial, we will learn about the getEncoding() method of the InputStreamReader class in Java, which is used to get the character encoding used by the stream, which may be historical or canonical, depending upon the same.