Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. Java
  4. Mastering File I/O in Java: A Comprehensive Guide to Reading and Writing Files

Mastering File I/O in Java: A Comprehensive Guide to Reading and Writing Files

Date- Mar 16,2026 35
java file io

Overview of File I/O in Java

File I/O in Java refers to the process of reading from and writing to files using the Java programming language. It allows programs to interact with external data, enabling them to store information permanently and retrieve it when needed. This capability is essential for applications that require persistence, such as saving user data, configuration settings, or logs. Java provides a robust set of classes in the java.io and java.nio packages to handle file operations efficiently.

Prerequisites

  • Basic understanding of Java programming language
  • Familiarity with Java Development Kit (JDK) and Integrated Development Environment (IDE)
  • Knowledge of exception handling in Java
  • Basic understanding of file systems and file formats

Reading Files in Java

Reading files in Java can be accomplished using different classes, primarily FileReader and BufferedReader. The FileReader class is used to read character files, while BufferedReader helps in reading text from a character-input stream efficiently.

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

public class FileReadExample {
    public static void main(String[] args) {
        BufferedReader reader = null;
        try {
            // Create a FileReader instance to read a file
            FileReader fileReader = new FileReader("example.txt");
            // Wrap FileReader in BufferedReader for efficient reading
            reader = new BufferedReader(fileReader);
            String line;
            // Read the file line by line
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // Close the BufferedReader to free up resources
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

In the above code:

  • import java.io.BufferedReader;: Imports the BufferedReader class for reading text from input streams.
  • import java.io.FileReader;: Imports the FileReader class for reading character files.
  • import java.io.IOException;: Imports the IOException class for handling input/output exceptions.
  • BufferedReader reader = null;: Initializes a BufferedReader variable to null.
  • FileReader fileReader = new FileReader("example.txt");: Creates a FileReader object to read from "example.txt".
  • reader = new BufferedReader(fileReader);: Wraps the FileReader in a BufferedReader for efficient reading of text.
  • while ((line = reader.readLine()) != null): Reads the file line by line until the end of the file is reached.
  • System.out.println(line);: Prints each line read from the file to the console.
  • reader.close();: Closes the BufferedReader to release system resources.

Writing Files in Java

Writing files in Java can be performed using the FileWriter and BufferedWriter classes. The FileWriter class enables writing character files, while BufferedWriter provides buffering for efficient writing.

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

public class FileWriteExample {
    public static void main(String[] args) {
        BufferedWriter writer = null;
        try {
            // Create a FileWriter instance to write to a file
            FileWriter fileWriter = new FileWriter("output.txt");
            // Wrap FileWriter in BufferedWriter for efficient writing
            writer = new BufferedWriter(fileWriter);
            // Write content to the file
            writer.write("Hello, World!\n");
            writer.write("This is a test file.\n");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // Close the BufferedWriter to free up resources
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

In the above code:

  • BufferedWriter writer = null;: Initializes a BufferedWriter variable to null.
  • FileWriter fileWriter = new FileWriter("output.txt");: Creates a FileWriter object to write to "output.txt".
  • writer = new BufferedWriter(fileWriter);: Wraps the FileWriter in a BufferedWriter for efficient writing.
  • writer.write("Hello, World!\n");: Writes the string "Hello, World!" to the file followed by a newline.
  • writer.write("This is a test file.\n");: Writes another line to the file.
  • writer.close();: Closes the BufferedWriter to release system resources.

Using Java NIO for File I/O

The java.nio package provides a more modern approach to file I/O compared to the traditional java.io package. The Files class in this package allows for convenient file operations, including reading and writing files using Paths.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;

public class NioFileExample {
    public static void main(String[] args) {
        Path path = Paths.get("example.txt");
        try {
            // Read all lines from the file into a List
            List lines = Files.readAllLines(path);
            // Print each line
            for (String line : lines) {
                System.out.println(line);
            }
            // Write new lines to the file
            Files.write(path, "New Line 1\nNew Line 2\n".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the above code:

  • Path path = Paths.get("example.txt");: Creates a Path object that represents the file "example.txt".
  • List lines = Files.readAllLines(path);: Reads all lines from the file into a List of strings.
  • for (String line : lines): Iterates over each line in the List.
  • System.out.println(line);: Prints each line read from the file to the console.
  • Files.write(path, "New Line 1\nNew Line 2\n".getBytes());: Writes new lines to the file as bytes.

File I/O Error Handling

When dealing with file I/O in Java, it's essential to handle exceptions properly to ensure that your program can respond gracefully to errors. The IOException is the primary exception that you will encounter when performing file operations.

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

public class ErrorHandlingExample {
    public static void main(String[] args) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("nonexistent.txt"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("An I/O error occurred: " + e.getMessage());
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                System.out.println("Error closing reader: " + ex.getMessage());
            }
        }
    }
}

In the above code:

  • catch (FileNotFoundException e): Catches the exception if the specified file does not exist.
  • System.out.println("File not found: " + e.getMessage());: Prints a user-friendly message indicating that the file was not found.
  • catch (IOException e): Catches any I/O exceptions that may occur during reading.
  • System.out.println("An I/O error occurred: " + e.getMessage());: Prints the error message for I/O exceptions.

Best Practices and Common Mistakes

Here are some best practices to follow when performing file I/O in Java:

  • Always close your streams: Use a finally block or try-with-resources statement to ensure that resources are released.
  • Use Buffered Streams: Utilize BufferedReader and BufferedWriter for efficient reading and writing.
  • Handle Exceptions: Always handle I/O exceptions gracefully to prevent your application from crashing.
  • Avoid Hardcoding Paths: Use relative paths or configuration files to specify file locations.

Conclusion

File I/O is a fundamental aspect of Java programming that every developer should master. This guide covered reading and writing files using both the traditional java.io package and the modern java.nio package. Remember to handle exceptions properly and follow best practices to ensure your file operations are efficient and error-free. With these skills, you can effectively manage data in your Java applications.

S
Shubham Saini
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Mastering File IO in Python: Comprehensive Guide to Reading and Writing Files
Mar 27, 2026
Mastering File I/O in C#: A Comprehensive Guide to Reading and Writing Files
Mar 16, 2026
Mastering Exception Handling in Java: A Comprehensive Guide
Mar 16, 2026
Understanding Lambda Expressions in Java: A Comprehensive Guide
Mar 16, 2026
Previous in Java
Mastering Multithreading in Java: A Comprehensive Guide
Next in Java
Spring Boot Tutorial for Beginners: Building a RESTful Applicatio…
Buy me a pizza

Comments

On this page

🎯

Interview Prep

Ace your Java interview with curated Q&As for all levels.

View Java Interview Q&As

More in Java

  • User-defined data types in java 6266 views
  • Master Java Type Casting: A Complete Guide with Examples 6237 views
  • How to add (import) java.util.List; in eclipse 5828 views
  • org.openqa.selenium.SessionNotCreatedException: session not … 5769 views
  • java.lang.IllegalStateException: The driver executable does … 5110 views
View all Java posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor