Signup/Sign In
PUBLISHED ON: MARCH 1, 2021

OutputStreamWriter close() Method in Java

In this tutorial, we will learn about the close() method of OutputStreamWriter class in Java. close() method is available in java.io package. This method closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect.

Syntax

This is the syntax of the close() method. The return type of the method is void, it returns nothing.

 public void close();

Example 1

In this example, we created the OutputStreamWriter object and we are writing the data to it and after that, we call the close() method and This method closes the stream, flushing it first.

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.close();	
		}
		catch (Exception e)
		{
			System.out.print("Error: "+e.toString());
		}
	} 
}

output.txt

A

Example 2

In this example, we created the OutputStreamWriter object and we are writing the data to it and after that, we call the close() method and This method closes the stream, flushing it first.

import java.io.FileInputStream;
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 os = new FileOutputStream("E:\\studytonight\\output.txt");
	         OutputStreamWriter writer = new OutputStreamWriter(os);

	         FileInputStream in = new FileInputStream("E:\\studytonight\\output.txt");

	         writer.write('S');

	         writer.close();

	         System.out.println("" + (char) in.read());
		}
		catch (Exception e)
		{
			System.out.print("Error: "+e.toString());
		}
	} 
}


S

output.txt

S

Conclusion

In this tutorial, we will learn about OutputStreamWriter close() method in Java. close() method is used to the first flush before closing the stream and the method write() or flush() invokes after closing the stream will result in an exception.



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.