File Writing in Java
What is File Writing?
File Writing in Java is the process of writing data (text or characters) into a file stored on the system. Java provides the FileWriter class to perform file writing operations efficiently.
The FileWriter class is part of the java.io package and is mainly used to write character-based data into a file.
FileWriter Class
- Package: java.io
- Purpose: Writes character data to a file
- Type: Character Output Stream
FileWriter Constructor
FileWriter(String filePath) throws IOException
Explanation:
- filePath → Location where the file is created or written
- Throws IOException → Handles input/output errors
📌 If the file does not exist, Java creates a new file automatically.
📌 If the file exists, Java overwrites its content (unless append mode is used).
FileWriter Methods
write(String str). Writes text into the output stream
flush(). Pushes data from buffer to file
close(). Closes the output stream
All methods throw IOException.
Steps to Perform File Writing Operation
Step 1: Create a FileWriter Object
To write data into a file, the programmer must first create an object of the FileWriter class.
FileWriter fw = new FileWriter("example.txt");
🔹 When the object is created, Java internally requests the Operating System to open an output stream for the file.
Step 2: Write Data into the File
Use the write() method to send content to the output stream.
fw.write("Welcome to Java File Writing");
📌 At this stage, data is stored in the buffer, not directly in the file.
Step 3: Flush the Data
The flush() method forces Java to transfer data from the buffer to the actual file.
📌 This ensures that all written content is saved properly.
Step 4: Close the FileWriter
After completing the file writing operation, the programmer must close the stream.
📌 Closing the stream releases system resources and prevents memory leaks.
Complete Example Program
import java.io.FileWriter;
import java.io.IOException;
public class FileWritingDemo {
public static void main(String[] args) {
FileWriter fw = new FileWriter("sample.txt");
fw.write("Java File Writing Example");
System.out.println("File written successfully");
} catch (IOException e) {
Real-Life Example
📘 Notebook Example:
Writing notes in a notebook is similar to file writing:
- Opening notebook → Creating FileWriter
- Writing notes → write()
- Pressing pages properly → flush()
- Closing notebook → close()
Important Points for Exams
- FileWriter is used for character-based output
- It belongs to the java.io package
- flush() ensures data safety
- close() is mandatory
- Throws IOException
- Overwrites file by default
Summary
- File Writing allows storing data permanently
- FileWriter is simple and beginner-friendly
- Always use flush() and close() after writing
- Proper exception handling is required
Comments
Post a Comment