Lesson 48 of 50 – Writing Files in Java
96%

Writing Files in Java

Java allows us to create files and write text into them. We can use FileWriter, BufferedWriter, and the Files class to write data.

1. Introduction to Writing Files

Writing a file means storing information in a file. For example, a Java program can save a student's name, marks, or a message in a text file.

Example file content:

Welcome to Java!
This is my first file.

Java provides several classes and methods for writing data to files.

2. Writing a File Using FileWriter

The FileWriter class is used to write characters into a text file.

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

public class Main {
    public static void main(String[] args) {
        try (FileWriter writer =
                 new FileWriter("message.txt")) {

            writer.write("Welcome to Java File Handling!");

            System.out.println("File written successfully.");

        } catch (IOException e) {
            System.out.println("An error occurred.");
        }
    }
}

Output:

File written successfully.

This creates message.txt if it does not exist. If the file already exists, its previous contents are overwritten.

3. Writing Multiple Lines

Use the newline character \n to place text on separate lines.

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

public class Main {
    public static void main(String[] args) {
        try (FileWriter writer =
                 new FileWriter("students.txt")) {

            writer.write("Rahul\n");
            writer.write("Amit\n");
            writer.write("Priya\n");

            System.out.println("Student names saved.");

        } catch (IOException e) {
            System.out.println("Unable to write file.");
        }
    }
}

Content of students.txt:

Rahul
Amit
Priya

4. Appending Data to a File

Appending means adding new content to the end of an existing file without removing its previous contents.

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

public class Main {
    public static void main(String[] args) {
        try (FileWriter writer =
                 new FileWriter("message.txt", true)) {

            writer.write("\nThis line is added later.");

            System.out.println("Data appended successfully.");

        } catch (IOException e) {
            System.out.println("Unable to append data.");
        }
    }
}

The second argument true enables append mode. If the file does not exist, Java creates it.

Remember: new FileWriter("message.txt") overwrites existing contents, while new FileWriter("message.txt", true) appends new data.

5. Writing a File Using BufferedWriter

BufferedWriter writes text efficiently by buffering characters. Its newLine() method adds a line separator.

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

public class Main {
    public static void main(String[] args) {
        try (BufferedWriter writer =
                 new BufferedWriter(
                     new FileWriter("details.txt"))) {

            writer.write("Name: Rahul");
            writer.newLine();

            writer.write("Course: Java");
            writer.newLine();

            writer.write("Marks: 85");

            System.out.println("Details saved successfully.");

        } catch (IOException e) {
            System.out.println("Unable to write file.");
        }
    }
}

File content:

Name: Rahul
Course: Java
Marks: 85

6. Creating a File Before Writing

You can use the File class to create a file explicitly before writing data.

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

public class Main {
    public static void main(String[] args) {
        try {
            File file = new File("newfile.txt");

            if (file.createNewFile()) {
                System.out.println("File created.");
            } else {
                System.out.println("File already exists.");
            }

            try (FileWriter writer = new FileWriter(file)) {
                writer.write("Hello from Java!");
            }

            System.out.println("Data written successfully.");

        } catch (IOException e) {
            System.out.println("An error occurred.");
        }
    }
}

The createNewFile() method creates a new, empty file only if it does not already exist.

7. Writing Data Using the Files Class

Java 11 and later provide Files.writeString() for writing a string to a file.

import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try {
            Path path = Path.of("message.txt");

            Files.writeString(
                path,
                "Hello! This file was written using Files."
            );

            System.out.println("File written successfully.");

        } catch (IOException e) {
            System.out.println("Unable to write file.");
        }
    }
}

This method creates the file if it does not exist and replaces its contents if it already exists.

8. Appending Text Using the Files Class

Use StandardOpenOption.APPEND to add text to an existing file.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try {
            Path path = Path.of("message.txt");

            Files.writeString(
                path,
                "\nNew content added.",
                StandardOpenOption.CREATE,
                StandardOpenOption.APPEND
            );

            System.out.println("Content appended.");

        } catch (IOException e) {
            System.out.println("Unable to append content.");
        }
    }
}

CREATE allows Java to create the file if it does not exist. APPEND adds content at the end.

9. Writing Student Information

The following example saves student information in a text file.

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

public class Main {
    public static void main(String[] args) {
        String name = "Rahul";
        int marks = 90;
        String course = "Java";

        try (FileWriter writer =
                 new FileWriter("student.txt")) {

            writer.write("Name: " + name + "\n");
            writer.write("Marks: " + marks + "\n");
            writer.write("Course: " + course + "\n");

            System.out.println("Student information saved.");

        } catch (IOException e) {
            System.out.println("Unable to save student information.");
        }
    }
}

File content:

Name: Rahul
Marks: 90
Course: Java

10. Writing a List of Lines

You can write multiple lines using Files.write() and a list of strings.

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        List<String> names =
            List.of("Rahul", "Amit", "Priya");

        try {
            Files.write(Path.of("names.txt"), names);
            System.out.println("Names saved successfully.");

        } catch (IOException e) {
            System.out.println("Unable to save names.");
        }
    }
}

Each string is written as a separate line. The file is created if necessary, and an existing file is normally truncated before the new content is written.

11. Difference Between Writing and Appending

Writing Appending
Replaces existing content by default. Keeps existing content and adds more.
Uses new FileWriter("data.txt"). Uses new FileWriter("data.txt", true).
Useful for saving fresh content. Useful for adding records or log entries.

12. Common Errors and Best Practices

  • Use the correct file path.
  • Handle IOException when writing files.
  • Use try-with-resources to close writers automatically.
  • Remember that normal write mode may erase previous content.
  • Use append mode when existing data must be preserved.
  • Make sure the program has permission to write to the destination.
  • Use an appropriate character encoding when required.
Important: Test file-writing programs with a sample file first. Overwriting a file can permanently replace its previous contents.

13. Practice Assignments

  1. Create a file named hello.txt and write a welcome message.
  2. Write your name, age, and city into a text file.
  3. Write five student names on separate lines.
  4. Append a new line to an existing file without deleting old content.
  5. Save student marks using FileWriter.
  6. Write three lines using BufferedWriter.
  7. Write text using Files.writeString().
  8. Create a simple program that saves a student's name and course.

🧠 Quick Quiz

1. Which class can write characters to a text file?




2. What does the second argument true mean in FileWriter?




3. Which method writes a string to a file in Java 11 and later?