Java file close


 

Java file close

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

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.

Ads