Lesson 46 of 50 – Java File Handling
92%

Java File Handling

File handling in Java allows programs to create, read, write, append, and manage files. Java provides classes such as File, FileReader, FileWriter, BufferedReader, and the modern Files utility.

1. What Is File Handling?

File handling means working with files stored on a computer. A Java program can use file handling to save information permanently instead of keeping it only in memory.

Common file operations include:

  • Creating a file
  • Writing data to a file
  • Reading file contents
  • Appending new content
  • Checking whether a file exists
  • Deleting a file
Example: A student management application can save student details in a text file and read them later.
2. The File Class

The java.io.File class represents a file or directory path. It provides methods to check existence, inspect names, and perform certain file-system operations.

import java.io.File;

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

        System.out.println(file.getName());
        System.out.println(file.exists());
    }
}
Example Output:
data.txt
false

The second line is false if data.txt does not exist at the path resolved from the program's working directory.

3. Creating a File

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

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

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

            if (file.createNewFile()) {
                System.out.println("File created");
            } else {
                System.out.println("File already exists");
            }
        } catch (IOException e) {
            System.out.println("File creation failed");
        }
    }
}
Possible Output:
File created

The output depends on whether the file already exists and whether the program has permission to create it.

4. Writing to a File Using FileWriter

The FileWriter class writes characters to a text file. By default, this constructor overwrites existing content.

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

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

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

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

        } catch (IOException e) {
            System.out.println("Writing failed");
        }
    }
}
Output:
Data written successfully

After running the program, data.txt contains the text written by the program.

5. Reading a File Using Scanner

Scanner can read text from a file. The following example reads the file one line at a time.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        try (Scanner sc =
                 new Scanner(new File("data.txt"))) {

            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                System.out.println(line);
            }

        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        }
    }
}
Example Output:
Welcome to Java File Handling

This program prints each line until the file has no more lines to read.

6. Reading a File Using FileReader

FileReader reads character data from a text file. You can read one character at a time.

import java.io.FileReader;
import java.io.IOException;

class Main {
    public static void main(String[] args) {
        try (FileReader reader =
                 new FileReader("data.txt")) {

            int ch;

            while ((ch = reader.read()) != -1) {
                System.out.print((char) ch);
            }

        } catch (IOException e) {
            System.out.println("Reading failed");
        }
    }
}

The read() method returns -1 when the end of the file is reached.

FileReader is designed for character data. For byte-oriented files such as images, use byte streams or suitable file-copying utilities.
7. Appending Data to a File

To append text without replacing existing content, create FileWriter with the append argument set to true.

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

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

            writer.write(System.lineSeparator());
            writer.write("This is a new line.");

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

        } catch (IOException e) {
            System.out.println("Appending failed");
        }
    }
}
Output:
Data appended successfully

The new text is added to the end of the file instead of replacing its previous contents.

8. Reading a File Using BufferedReader

BufferedReader reads text efficiently by buffering characters and provides a convenient readLine() method.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class Main {
    public static void main(String[] args) {
        try (BufferedReader reader =
                 new BufferedReader(
                     new FileReader("data.txt"))) {

            String line;

            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

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

The loop continues until readLine() returns null, which means there are no more lines.

9. Checking File Information

The File class provides methods for checking basic information about a path.

import java.io.File;

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

        System.out.println("Name: " + file.getName());
        System.out.println("Exists: " + file.exists());
        System.out.println("Readable: " + file.canRead());
        System.out.println("Writable: " + file.canWrite());
        System.out.println("Size: " + file.length());
    }
}

The results depend on the actual file and the operating system's permissions.

Note: length() returns the file size in bytes for an ordinary file. Its value is not a character count for text files.

10. Deleting a File

The delete() method attempts to delete a file or an empty directory.

import java.io.File;

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

        if (file.delete()) {
            System.out.println("File deleted");
        } else {
            System.out.println(
                "File could not be deleted"
            );
        }
    }
}

The delete() method returns true if the deletion succeeds and false otherwise.

Warning: This operation can permanently remove the file. Test with a sample file before using deletion code on important data.
11. Modern File Handling Using Files and Path

The java.nio.file package provides modern utilities for working with paths and files. Files.writeString() and Files.readString() are available in Java 11 and later.

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

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

        try {
            Files.writeString(
                path,
                "Hello from Java NIO"
            );

            String content = Files.readString(path);

            System.out.println(content);

        } catch (IOException e) {
            System.out.println("File operation failed");
        }
    }
}
Output:
Hello from Java NIO

Files.writeString() creates the file if necessary and replaces its existing content by default. Files.readString() reads the file as a string.

12. Best Practices for File Handling
  • Use try-with-resources to close file resources automatically.
  • Handle IOException and other relevant exceptions.
  • Use clear file paths and understand the program's working directory.
  • Use append mode when existing content must be preserved.
  • Avoid deleting or overwriting important files without checking the target path.
  • Choose character streams for text and byte streams for binary data.
Remember: Closing a file resource correctly helps release operating system resources and avoids resource leaks.
13. Practice Assignments
  1. Create a file named student.txt.
  2. Write your name, course, and city into a text file.
  3. Read the contents of a file using Scanner.
  4. Read a file line by line using BufferedReader.
  5. Append a new line to an existing file.
  6. Display a file's name, size, and existence status.
  7. Write a program that deletes a test file.
  8. Use Files.writeString() and Files.readString() to write and read text.
Practice Tip: Run each program from a known working directory so you can easily locate the files it creates.

🧠 Quick Quiz

1. Which class can create a new empty file?




2. How do you append text using FileWriter?




3. Which method reads a complete text file into a String in Java 11 and later?