JAVA - Zero to Hero / File Handling

Writing to a File

📌 Why Write to a File?

Imagine you want your Java program to:

  • Save a user’s name or score in a quiz

  • Create a log of user actions

  • Store messages permanently

  • Save reports for later use

To do this, we need to write data from the program into a file — that's called file writing.


🧰 Tool Used: FileWriter

Java provides the FileWriter class (in java.io package) to write text into files. It allows you to write characters (letters, numbers, etc.) into a file on your computer.


🔧 How it works (Simple Concept):

  1. You create a FileWriter object and give it a file name (e.g. "output.txt").

  2. You use .write() to send text to that file.

  3. You use .close() to save and close the file (very important!).


✅ Basic Java Program to Write to a File

import java.io.FileWriter;
import java.io.IOException;

public class WriteFileExample {
    public static void main(String[] args) {
        try {
            // Step 1: Create FileWriter object linked to a file named "output.txt"
            FileWriter fw = new FileWriter("output.txt");

            // Step 2: Write text to the file
            fw.write("Hello, World!\\n");
            fw.write("This is written using FileWriter in Java.\\n");

            // Step 3: Close the FileWriter to save changes
            fw.close();

            System.out.println("File written successfully.");
        } catch (IOException e) {
            System.out.println("An error occurred while writing to the file.");
            e.printStackTrace();
        }
    }
}
File written successfully.

🧾 Step-by-Step Explanation:

🔹 import java.io.FileWriter; and IOException

  • FileWriter is the class we use to write to files.

  • File operations can fail (e.g., the file is locked, disk is full), so Java requires you to handle exceptions like IOException.

🔹 FileWriter fw = new FileWriter("output.txt");

  • This creates or opens a file called output.txt.

  • If the file doesn't exist, Java creates it for you.

  • If the file already exists, its previous content is erased (this is called overwrite mode).

🔹 fw.write("Hello, World!\\n");

  • This line writes text into the file.

  • \\n adds a new line, just like pressing Enter in a text editor.

🔹 fw.close();

  • Think of fw (FileWriter) like a pen — when you're done writing, you put the pen away.

  • close() saves everything and releases memory.

  • If you forget to close it, the content may not be saved correctly.


📄 Content inside output.txt file:

Hello, World!
This is written using FileWriter in Java.

You’ll find this file in the same folder where your Java program runs.


✍️ What if you want to add more content without erasing what's already there?

By default, FileWriter erases old content. To append (add at the end), use this:

FileWriter fw = new FileWriter("output.txt", true);  // true means append

✅ Example: Appending to a File

import java.io.FileWriter;
import java.io.IOException;

public class AppendFileExample {
    public static void main(String[] args) {
        try {
            // Open the file in append mode
            FileWriter fw = new FileWriter("output.txt", true);

            fw.write("This line is appended.\\n");

            fw.close();
            System.out.println("Content appended successfully.");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

📄 Now your output.txt file looks like:

Hello, World!
This is written using FileWriter in Java.
This line is appended.

🧠 Summary: Why Each Step Matters

Step

Why it's Needed

FileWriter fw = new FileWriter("filename")

Opens or creates the file

fw.write("text")

Sends the text to the file

fw.close()

Saves and closes the file (must-do!)

try-catch block

Handles possible file writing errors safely


❓ Common Beginner Questions

Q: What if the file doesn’t exist?

✅ No problem! FileWriter creates it for you automatically.

Q: What if I don’t close the file?

⚠️ Data might not be saved properly. Always close using .close().

Q: Where is the file saved?

📂 It’s saved in the project’s root directory (same folder where .java runs from).

Q: Can I write user input into the file?

✅ Yes! Use Scanner to take input and FileWriter to write it.


👨🏻‍💻 Bonus: Writing User Input to a File

import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;

public class UserInputToFile {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        try {
            FileWriter fw = new FileWriter("userinput.txt");
            System.out.print("Enter your name: ");
            String name = sc.nextLine();

            fw.write("Name: " + name + "\\n");

            fw.close();
            System.out.println("User input written to file.");
        } catch (IOException e) {
            System.out.println("Error writing to file.");
            e.printStackTrace();
        }
        sc.close();
    }
}

Console:

Enter your name: Aanya
User input written to file.

File: userinput.txt

Name: Aanya