How to Read, Write, and Manage Files in Java

Markdown

View as Markdown

File handling is an essential part of Java programming that allows applications to create, read, update, and manage data stored in external files. Whether you're building student management systems, inventory applications, or database-driven solutions, file handling enables programs to store information permanently rather than keeping it only during program execution.

Java provides several built-in classes that make working with files simple and efficient. In this article, you'll learn how to create files, read and write data, delete files, and use classes such as File, FileReader, FileWriter, BufferedReader, and BufferedWriter.

Learning Objectives

  • Create files using Java.

  • Write data into files.

  • Read data from files.

  • Delete files when they are no longer required.

  • Work with FileReader and FileWriter.

  • Use BufferedReader and BufferedWriter efficiently.

  • Handle exceptions while performing file operations.

What is File Handling?

File handling allows Java programs to:

  • Store information permanently.

  • Read existing data from files.

  • Write new information into files.

  • Update file contents.

  • Manage application data efficiently.

Common examples include:

  • Student records

  • Employee information

  • Reports and logs

  • Configuration files

  • Application-generated documents

The File Class

The File class is used to create, access, and manage files and directories.

Before using the File class, import:

import java.io.File;

Example

import java.io.File;

public class FileExample {

    public static void main(String[] args) {

        File file = new File("Student.txt");

        System.out.println(file.exists());

    }

}

This program checks whether the file exists.

Creating a File

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

Example

import java.io.File;

import java.io.IOException;

public class CreateFile {

    public static void main(String[] args) {

        try {

            File file = new File("Student.txt");

            if (file.createNewFile()) {

                System.out.println("File Created Successfully.");

            } else {

                System.out.println("File Already Exists.");

            }

        }

        catch (IOException e) {

            System.out.println("An error occurred.");

        }

    }

}

Output

File Created Successfully.

Writing Data into a File

The FileWriter class is used to write data into files.

Example

import java.io.FileWriter;

import java.io.IOException;

public class WriteFile {

    public static void main(String[] args) {

        try {

            FileWriter writer = new FileWriter("Student.txt");

            writer.write("Welcome to Java Programming.");

            writer.close();

 

            System.out.println("Data Written Successfully.");

        }

        catch (IOException e) {

            System.out.println("Unable to Write Data.");

        }

    }

}

Output

Data Written Successfully.

The text is now stored inside the file.

 

Reading Data from a File

The FileReader class reads characters from a file.

Example

import java.io.FileReader;

import java.io.IOException;

public class ReadFile {

    public static void main(String[] args) {

        try {

            FileReader reader =

                    new FileReader("Student.txt");

            int character;

            while ((character = reader.read()) != -1) {

                System.out.print((char) character);

 

            }

            reader.close();

        }

        catch (IOException e) {

            System.out.println("Unable to Read File.");

        }

    }

}

Output

Welcome to Java Programming.

Deleting a File

The delete() method removes a file from the system.

Example

import java.io.File;

public class DeleteFile {

    public static void main(String[] args) {

        File file = new File("Student.txt");

        if(file.delete()) {

            System.out.println("File Deleted Successfully.");

        }

        else {

            System.out.println("Unable to Delete File.");

        }

 

    }

}

Output

File Deleted Successfully.

Using FileReader

FileReader is suitable for reading character-based files.

Example

FileReader reader =

        new FileReader("Student.txt");

It is commonly used for:

  • Reading text files

  • Processing character data

  • Reading application configuration files

Using FileWriter

FileWriter writes character data into files.

Example

FileWriter writer =

        new FileWriter("Student.txt");

It is useful for:

  • Writing reports

  • Saving application data

  • Exporting information into text files

Using BufferedReader

BufferedReader improves reading performance by reading larger chunks of data at once.

 

Example

import java.io.*;

public class BufferedReaderExample {

    public static void main(String[] args) {

        try {

            BufferedReader reader =

                    new BufferedReader(

                            new FileReader("Student.txt"));

            String line;

            while((line = reader.readLine()) != null) {

                System.out.println(line);

            }

            reader.close();

        }

        catch(IOException e) {

            System.out.println("Error Reading File.");

        }

    }

}

Output

Welcome to Java Programming.

BufferedReader is particularly useful when reading large text files.

 

 

Using BufferedWriter

BufferedWriter improves writing performance by buffering output before saving it to the file.

Example

import java.io.*;

public class BufferedWriterExample {

    public static void main(String[] args) {

        try {

            BufferedWriter writer =

                    new BufferedWriter(

                            new FileWriter("Student.txt"));

            writer.write("Java File Handling");

            writer.newLine();

            writer.write("Learning BufferedWriter.");

            writer.close();

        }

        catch(IOException e) {

            System.out.println("Error Writing File.");

        }

    }

}

Output

Java File Handling

Learning BufferedWriter.

  

Appending Data to a File

You can preserve existing file contents by enabling append mode.

Example

FileWriter writer =

        new FileWriter("Student.txt", true);

writer.write("\nWelcome Back!");

writer.close();

Output

Welcome to Java Programming.

Welcome Back!

Exception Handling in File Operations

File operations may generate exceptions such as:

  • FileNotFoundException

  • IOException

  • SecurityException

Always use exception handling when working with files.

Example

try {

    // File operations

}

catch(IOException e) {

    System.out.println("An error occurred.");

}

Handling exceptions improves application reliability and prevents unexpected program failures.

Real-World Applications

File handling is widely used in:

  • Student Management Systems

  • Banking Applications

  • Inventory Management Systems

  • Payroll Systems

  • Attendance Management Systems

  • Report Generation Systems

  • Enterprise Applications

Almost every software application performs some form of file management.

Common Mistakes

Avoid these common errors when working with files:

  • Forgetting to close file streams.

  • Attempting to read a file that does not exist.

  • Ignoring exception handling.

  • Accidentally overwriting existing files.

  • Using FileReader for binary files.

  • Forgetting to enable append mode when required.

Practice Exercise

Write Java programs to:

  1. Create a text file named Student.txt.

  2. Write student information into the file.

  3. Read and display the file contents.

  4. Append additional information to the existing file.

  5. Delete the file.

  6. Read multiple lines using BufferedReader.

  7. Write multiple lines using BufferedWriter.

  8. Handle exceptions during all file operations.

Was this article helpful?

Still need help?

Contact us