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

OutputStreamWriter getEncoding() Method in Java

In this tutorial, we will learn about the getEncoding() method of OutputStreamWriter class in Java. 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.

Syntax

This is the syntax declaration of the getEncoding() method, it does not take any parameter and returns the encoding of the corresponding stream.

public String getEncoding()

Example 1

In this example, we are writing the data to the file. Once we write the text into the OutputStream that stream data has a particular encoding. To check that encoding we will call the method getEncoding() to check the encoding of the stream.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
class StudyTonight
{
	public static void main(String[] args) throws IOException 
	{ 
		try 
		{
			OutputStream outputStream = new FileOutputStream("E:\\studytonight\\output.txt");
			OutputStreamWriter writer = new OutputStreamWriter(outputStream);
			writer.write('A');
			writer.flush();
			System.out.println("" + writer.getEncoding());
		} 
		catch (Exception e)
		{
			System.out.print("Error: "+e.toString());
		}
	} 
}


Cp1252

Example 2

In this example, we are writing the data to the file. Once we write the text into the OutputStream that stream data has a particular encoding. To check that encoding we will call the method getEncoding() to check the encoding of the stream.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
class StudyTonight
{
	public static void main(String[] args) throws IOException 
	{ 
		char arr[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'};
		try
		{
			OutputStream outputStream = new FileOutputStream("E:\\studytonight\\output.txt");
			OutputStreamWriter writer = new OutputStreamWriter(outputStream);

			writer.write(arr, 3, 5);
			
			System.out.print("Encoding: "+writer.getEncoding());
			
			writer.flush();	
		}
		catch (Exception e)
		{
			System.out.print("Error: "+e.toString());
		}
	} 
}


Encoding: Cp1252

Conclusion

In this tutorial, we learned about the getEncoding() method of OutputStreamWriter class in Java. This method returns the name of the character encoding being used by this stream.