Close a File in Java

Classes for input and output operations can be found in the java.io package
. This package contains input and output streams for reading and writing data to files.
We’ll use the close()
method to flush out the stream after executing any file operations.
Use the close()
Method to Close a File in Java
The BufferedWriter
class is utilized in the following program. This class allows you to efficiently write arrays, strings, and characters into a character-output stream.
We also employ the FileWriter
class, designed for writing streams of characters, and the BufferedWriter
class.
A file path is represented by an instance of the File
class file. An abstract pathname is constructed from the specified pathname string.
The BufferedWriter
’s write()
method saves some text to the file. The newLine()
method adds a /n
as a line separator.
The majority of streams don’t need to be closed after being used. When the source is an Input/Output Channel, it is recommended to close the stream.
We should invoke the close()
method before terminating the program or executing any file operations. We might lose some data if we don’t.
As a result, to close the stream and keep the data secure, the close()
method is utilized.
Streams include a method called BaseStream.close()
, which implements Autoclosable
. Almost all stream instances don’t need to be closed because they’re supported by collections, which are arrays that don’t need any additional resource management.
The stream should be closed if the source is an IO channel.
The contents of the file are shown below before conducting the write operation.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class CloseFile {
public static void main(String[] args) throws Exception {
File file = new File("/Users/John/Temp/demo1.txt");
if (file.exists()) {
BufferedWriter bufferWriter = new BufferedWriter(new FileWriter(file, true));
bufferWriter.write("New Text");
bufferWriter.newLine();
bufferWriter.close();
}
}
}
After performing the write operation, the file’s contents changed.
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
LinkedInRelated Article - Java File
- Remove Line Breaks Form a File in Java
- FileFilter in Java
- File Separator in Java
- Get File Size in Java
- Read Bytes From a File in Java
- Delete Files in a Directory Using Java