Share on Google+Share on Google+

Java file close

This section demonstrates you the use of close() method.

Java file close

This section demonstrates you the use of close() method.

Description of code:

Streams represent resources which is to be clean up explicitly. You can done this using the method close(). This method automatically flush out the stream. It is necessary to close the stream after performing any file operation before exiting the program otherwise you could lose buffered data.

In the given example, we have used BufferedWriter class along with FileWriter class to write some text to the file. The method write() of BufferedWriter class writes the text into the file. The method newLine() writes the line separator and using the method close(), we have closed the stream and keep the data safe.

Here is the code:


public class FileClose {
	public static void main(String[] args) throws Exception {
		File file = new File("C:/data.txt");
		if (file.exists()) {
			BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));

In the above code, we have used close() method to flush out the stream. It is essential as it could leak the resources.


Posted on: April 14, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.