JAVA Tutorial
Estimated reading: 4 minutes 32 views

πŸ“‚ Java File Handling – Read, Write, Create & Delete Files with Ease (2025)


🧲 Introduction – Why Learn Java File Handling?

In real-world applications, reading and writing files is a core requirementβ€”whether it’s saving user data, logs, configuration, or reports. Java’s java.io and java.nio packages provide robust tools to manage file operations.

🎯 In this guide, you’ll learn:

  • How to create and write to files
  • How to read content from files
  • How to delete files using Java
  • Best practices for file handling

πŸ“Œ Topics Covered

πŸ”’ TopicπŸ“˜ Description
Java FilesIntroduction to file management in Java
Java Create/Write FilesCreating and writing text into files
Java Read FilesReading content line-by-line
Java Delete FilesDeleting existing files using File.delete()

πŸ“ Java Files – File Class Overview

Java provides the File class (from java.io) to represent file and directory pathnames.

πŸ§ͺ Example: Checking if a file exists

import java.io.File;

public class FileCheck {
  public static void main(String[] args) {
    File file = new File("example.txt");
    if (file.exists()) {
      System.out.println("File exists.");
    } else {
      System.out.println("File does not exist.");
    }
  }
}

πŸ” Line-by-Line Explanation:

  • File file = new File(...) β†’ Represents a file or path
  • file.exists() β†’ Checks if the file physically exists

πŸ“ Java Create/Write Files – FileWriter

You can use FileWriter or BufferedWriter to create and write to files.

πŸ§ͺ Example:

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

public class WriteFile {
  public static void main(String[] args) {
    try {
      FileWriter writer = new FileWriter("output.txt");
      writer.write("Welcome to Java File Handling!");
      writer.close();
      System.out.println("Successfully written to the file.");
    } catch (IOException e) {
      System.out.println("An error occurred.");
    }
  }
}

πŸ” Line-by-Line Explanation:

  • FileWriter writer = new FileWriter(...) β†’ Creates or opens the file
  • writer.write(...) β†’ Writes content
  • writer.close() β†’ Closes the file (important for saving data)

πŸ“– Java Read Files – FileReader/BufferedReader

Java supports reading files using FileReader, BufferedReader, or Scanner.

πŸ§ͺ Example (BufferedReader):

import java.io.*;

public class ReadFile {
  public static void main(String[] args) {
    try {
      BufferedReader reader = new BufferedReader(new FileReader("output.txt"));
      String line;
      while ((line = reader.readLine()) != null) {
        System.out.println(line);
      }
      reader.close();
    } catch (IOException e) {
      System.out.println("Unable to read file.");
    }
  }
}

πŸ” Line-by-Line Explanation:

  • BufferedReader + FileReader β†’ Opens file for reading
  • readLine() β†’ Reads each line until the end (null)
  • reader.close() β†’ Frees up system resources

πŸ—‘οΈ Java Delete Files – File.delete()

Use the delete() method to remove a file.

πŸ§ͺ Example:

import java.io.File;

public class DeleteFile {
  public static void main(String[] args) {
    File file = new File("output.txt");
    if (file.delete()) {
      System.out.println("Deleted: " + file.getName());
    } else {
      System.out.println("Failed to delete the file.");
    }
  }
}

πŸ” Line-by-Line Explanation:

  • file.delete() β†’ Attempts to delete the specified file
  • Returns true if successful, false otherwise

πŸ“Œ Summary – Recap & Next Steps

File handling in Java is essential for applications involving persistent storage, reporting, and configuration.

πŸ” Key Takeaways:

  • Use File, FileWriter, and BufferedReader for file manipulation
  • Always close streams to avoid memory leaks
  • Always handle exceptions using try-catch blocks
  • File.delete() allows cleanup of unneeded files

βš™οΈ What’s Next?

  • Learn about serialization for writing objects to files
  • Use java.nio.file.Files for advanced file operations
  • Try writing a log system or file-based database

❓ Frequently Asked Questions (FAQs)


❓ What is the difference between FileWriter and BufferedWriter?
βœ… FileWriter writes directly, while BufferedWriter buffers content before writing, improving performance for large files.


❓ Can I append data to a file instead of overwriting?
βœ… Yes! Use new FileWriter("file.txt", true) to enable append mode.


❓ What happens if the file doesn’t exist when reading?
❌ Java throws a FileNotFoundException, which must be handled using try-catch.


❓ Is it necessary to close the file after writing?
βœ… Absolutely. Not closing the file may result in unsaved data or resource leaks.


❓ Can I delete a directory using File.delete()?
βœ… Only if the directory is empty. Use Files.delete(Path) for more advanced deletion.


Share Now :

Leave a Reply

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

Share

πŸ“‚ Java File Handling

Or Copy Link

CONTENTS
Scroll to Top