Skip to content

📁 Java File Handling – Read, Write, and Process Files Like a Pro


🧠 Introduction

Java gives you powerful tools to work with files—whether you’re reading config files, writing logs, or processing data. In this lesson, you’ll learn how to read, write, and manipulate files and directories using Java.

This is essential for real-world applications like file upload/download, report generation, and log management.


🧰 File Handling Classes Overview

Class/InterfacePurpose
FileRepresents file or directory
FileReader/WriterRead/write character files
BufferedReaderEfficient reading of text
FileInputStreamRead byte streams (binary files)
FileOutputStreamWrite byte streams
Files (Java NIO)Advanced operations

📌 Creating a File

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

public class CreateFileExample {
    public static void main(String[] args) {
        File file = new File("example.txt");
        try {
            if (file.createNewFile()) {
                System.out.println("File created: " + file.getName());
            } else {
                System.out.println("File already exists.");
            }
        } catch (IOException e) {
            System.out.println("An error occurred.");
        }
    }
}

📝 Writing to a File

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

public class WriteFileExample {
    public static void main(String[] args) {
        try (FileWriter writer = new FileWriter("example.txt")) {
            writer.write("Hello from Java FileWriter!");
            System.out.println("Successfully written.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

📖 Reading from a File

🔹 Using BufferedReader

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

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);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

🔁 Append to File

try (FileWriter writer = new FileWriter("example.txt", true)) {
    writer.write("\nThis line is appended.");
}

🧪 Check If File Exists

File file = new File("example.txt");
if (file.exists()) {
    System.out.println("File exists.");
}

🧹 Delete a File

if (file.delete()) {
    System.out.println("Deleted the file: " + file.getName());
} else {
    System.out.println("Failed to delete the file.");
}

🗂️ Working with Directories

🔹 Create a Directory

File dir = new File("myfolder");
if (dir.mkdir()) {
    System.out.println("Directory created.");
}

🔹 List Files in Directory

File folder = new File("myfolder");
for (File f : folder.listFiles()) {
    System.out.println(f.getName());
}

💪 Java NIO – Modern File API

import java.nio.file.*;

public class NIOExample {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("niofile.txt");
        Files.write(path, "Written using NIO".getBytes());
        String content = Files.readString(path);
        System.out.println(content);
    }
}

🚨 Exception Handling Best Practices

✅ Always use try-with-resources to auto-close streams
✅ Catch and handle IOException
✅ Check if file exists before operations


🧠 Recap

  • Create, read, write, append, and delete files
  • Work with directories
  • Use classic IO and modern NIO API
  • Best practices with file streams

✅ What You Learned

  • Java File, FileReader, FileWriter, BufferedReader, and Files class usage
  • How to build file-handling features for your apps
  • Simple examples to get started with file management in Java

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *