Home Tutorial Java Core Files Java file close

 
 

Share on Google+Share on Google+
Java file close
Posted on: April 14, 2006 at 12:00 AM
Advertisement
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:

import java.io.*;

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));
			bw.write("Welcome");
			bw.newLine();
			bw.close();
		}
	}
}

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

Advertisement

Related Tags for Java file close:


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.

Posted on: April 14, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com