📁 Java File Handling: A Complete Guide for Beginners

Suraj ShindeSuraj Shinde
4 min read

File handling in Java is a crucial skill for any developer who works with data storage, configuration files, logs, or user input/output. Java provides rich APIs to read, write, and manipulate files through its standard library—making file handling both simple and powerful.

In this article, we’ll cover everything from basic file operations to advanced techniques using both java.io and java.nio packages.


🚀 What is File Handling?

File Handling refers to reading from and writing to files in the file system. Java makes this possible with built-in classes in:

  • java.io (older but commonly used)

  • java.nio.file (newer and more efficient)


📦 Java File Handling Classes

Class/InterfacePackageUse Case
Filejava.ioCreating, deleting, checking info
FileReaderjava.ioReading character files
FileWriterjava.ioWriting character files
BufferedReaderjava.ioReading text line by line
BufferedWriterjava.ioWriting text line by line
Filesjava.nio.fileAdvanced file operations
Pathsjava.nio.fileWorking with file paths

✍️ Writing to a File (FileWriter + BufferedWriter)

import java.io.*;

public class WriteFileExample {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("example.txt");
            BufferedWriter buffer = new BufferedWriter(writer);
            buffer.write("Hello, this is a Java file handling example!");
            buffer.newLine();
            buffer.write("Learning file write operations is easy.");
            buffer.close();
            System.out.println("File written successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

📖 Reading from a File (FileReader + BufferedReader)

import java.io.*;

public class ReadFileExample {
    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

🗂️ Creating and Deleting Files (Using File class)

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

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

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

            if (file.delete()) {
                System.out.println("File deleted: " + file.getName());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

🧾 Reading & Writing with java.nio.file.Files

The Files class is part of java.nio and offers powerful utilities for file operations in fewer lines of code.

Write:

import java.nio.file.*;
import java.io.IOException;
import java.util.*;

public class NIOWriteExample {
    public static void main(String[] args) {
        List<String> lines = Arrays.asList("Line 1", "Line 2", "Line 3");
        try {
            Files.write(Paths.get("niofile.txt"), lines);
            System.out.println("Written using NIO.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Read:

import java.nio.file.*;
import java.io.IOException;
import java.util.*;

public class NIOReadExample {
    public static void main(String[] args) {
        try {
            List<String> lines = Files.readAllLines(Paths.get("niofile.txt"));
            lines.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

🔐 Exception Handling in File Operations

Most file operations can throw IOException. Java encourages developers to handle exceptions using try-catch blocks or declare them using throws.

Best practice is to close streams using:

  • try-with-resources to automatically close readers/writers.
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
    // Read file
} catch (IOException e) {
    e.printStackTrace();
}

✅ Best Practices for Java File Handling

  1. Always close file resources using try-with-resources.

  2. Check file existence before performing operations.

  3. Use buffering to improve performance.

  4. Avoid hard-coded file paths — use Paths.get() and environment variables.

  5. Use java.nio for modern and efficient file handling.


🧠 Real-World Use Cases

  • Storing user data in a text file

  • Writing application logs

  • Reading configuration files

  • Loading data from CSV or JSON files

  • Generating reports


🧪 Mini Project Idea: Log Writer

Build a simple Logger class that:

  • Writes logs with timestamps

  • Appends new logs without overwriting

  • Saves logs to a daily .txt file


🔚 Conclusion

Java provides robust and flexible tools for file handling. Whether you're building a basic file reader or working on a large-scale file-processing system, Java's io and nio packages make it easy to manage file operations efficiently.

Mastering file handling prepares you for real-world backend, data processing, and application development tasks.

0
Subscribe to my newsletter

Read articles from Suraj Shinde directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Suraj Shinde
Suraj Shinde

I'm Suraj Parmeshwar Shinde, a passionate software developer from Tadshivani, Maharashtra, currently based in Pune. I’ve recently completed my Bachelor of Computer Applications (BCA) from Badrinarayan Barwale College, Jalna. During my graduation, I worked as a Software Intern at PRYM Aerospace Pvt. Ltd., where I contributed to the development of an AI-based crop advisory platform using technologies like Node.js, Flask, and React.js. This experience helped me gain hands-on knowledge of real-world software development and agile practices. For my final year project, I built Medicheck, a full-stack doctor appointment booking system using the MERN stack and Tailwind CSS. It features patient and admin panels, doctor profiles, secure Razorpay payments, and a mobile-responsive interface. My core technical skills include React.js, Node.js, Express.js, JavaScript, Java, MongoDB, SQL, and tools like Git, Postman, Docker, and Netlify. I’m a quick learner who enjoys building real-world applications, solving logical problems, and writing clean, maintainable code. Outside of tech, I enjoy driving and reading books. I’m always eager to grow, collaborate, and contribute to impactful technology solutions.