Signup/Sign In

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.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.