Explanation
This Java program demonstrates the basics of File Input/Output (I/O) operations using character streams. Specifically, it shows how to write text data into a local text file named Written.txt using the FileWriter class.
Here is a step-by-step breakdown of how the code works:
-
Importing the Required Class: The program starts by importing
java.io.FileWriter. This class is part of Java’s standard I/O package and is specifically designed for writing character files. -
Main Method and Exception Handling: The
mainmethod is declared withthrows Exception. Since file operations are prone to runtime errors (like permission issues or disk-full errors), Java requires these operations to handle or declare potentialIOExceptions. -
Defining the Data: A
Stringvariablestris initialized with the text content:"File handling in java using FileWriter and FileReader". -
Opening the File: The line
FileWriter fw = new FileWriter("Written.txt");instantiates aFileWriterobject. This action attempts to open a file namedWritten.txtin the program's local directory. If the file does not exist, Java automatically creates it. If it already exists, its contents will be overwritten by default. -
Writing Character-by-Character: The program uses a
forloop to iterate through each character of the stringstr.str.length()determines how many characters are in the string.str.charAt(i)extracts the character at the current indexi.fw.write(...)writes that single character into the file stream.
-
User Feedback: Once the loop finishes writing all characters,
System.out.println("Writing successful");prints a confirmation message to the console. -
Closing the Stream: Finally,
fw.close();is called. Closing the stream is a critical step because it flushes any buffered data directly into the physical file and releases system resources associated with the file.