Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev

File I/O and Serialization

File handling in Java allows programs to store data permanently, read data from files, and manipulate file systems. Java provides rich support for file operations through the java.io and java.nio packages. File handling is essential for applications such as logging systems, data storage, report generation, configuration management, and serialization.


1. File Class

What is File Class?

The File class (from java.io package) is used to represent a file or directory path.
It does not read or write data — it only provides metadata and file operations.


Common Uses

  • Create files and directories
  • Check file existence
  • Get file properties
  • Delete or rename files

Example

import java.io.File;

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

        System.out.println("Exists: " + file.exists());
        System.out.println("File name: " + file.getName());
        System.out.println("Absolute path: " + file.getAbsolutePath());
    }
}

2. Byte Streams and Character Streams

Java provides two types of streams for file handling.


2.1 Byte Streams

  • Used to handle binary data (images, audio, video)
  • Read/write byte by byte
  • Classes: FileInputStream, FileOutputStream

Example (Byte Stream Write)

import java.io.FileOutputStream;

public class ByteWrite {
    public static void main(String[] args) throws Exception {
        FileOutputStream fos = new FileOutputStream("data.bin");
        fos.write(65); // writes 'A'
        fos.close();
    }
}

2.2 Character Streams

  • Used for text data
  • Read/write character by character
  • Classes: FileReader, FileWriter

Example (Character Stream Read)

import java.io.FileReader;

public class CharRead {
    public static void main(String[] args) throws Exception {
        FileReader fr = new FileReader("sample.txt");
        int ch;
        while ((ch = fr.read()) != -1) {
            System.out.print((char) ch);
        }
        fr.close();
    }
}

Byte Stream vs Character Stream

Byte StreamCharacter Stream
Binary dataText data
Faster for mediaHandles Unicode
FileInputStreamFileReader

3. BufferedReader and BufferedWriter

Why Buffered Streams?

Buffered streams improve performance by reading or writing data in chunks instead of one character at a time.


BufferedReader

  • Reads text efficiently
  • Supports reading line by line

Example

import java.io.*;

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

BufferedWriter

  • Writes text efficiently
  • Supports newLine() method

Example

import java.io.*;

public class BufferedWrite {
    public static void main(String[] args) throws Exception {
        BufferedWriter bw = new BufferedWriter(new FileWriter("sample.txt"));
        bw.write("Welcome to Java File Handling");
        bw.newLine();
        bw.write("Buffered Writer Example");
        bw.close();
    }
}

4. Reading and Writing Files

Writing Data to File

  • FileWriter
  • BufferedWriter
  • FileOutputStream

Reading Data from File

  • FileReader
  • BufferedReader
  • FileInputStream

Combined Example

import java.io.*;

public class ReadWriteDemo {
    public static void main(String[] args) throws Exception {
        FileWriter fw = new FileWriter("info.txt");
        fw.write("Java File Handling");
        fw.close();

        FileReader fr = new FileReader("info.txt");
        int ch;
        while ((ch = fr.read()) != -1) {
            System.out.print((char) ch);
        }
        fr.close();
    }
}

5. Serialization and Deserialization

What is Serialization?

Serialization is the process of converting an object into a byte stream so that it can be stored in a file or sent over a network.

Deserialization

  • Converting byte stream back into an object

Requirements

  • Class must implement Serializable
  • Fields marked transient are not serialized

Serialization Example

import java.io.*;

class Student implements Serializable {
    int id;
    String name;

    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

public class SerializeDemo {
    public static void main(String[] args) throws Exception {
        Student s = new Student(1, "Prakash");

        ObjectOutputStream oos =
            new ObjectOutputStream(new FileOutputStream("student.ser"));
        oos.writeObject(s);
        oos.close();
    }
}

Deserialization Example

import java.io.*;

public class DeserializeDemo {
    public static void main(String[] args) throws Exception {
        ObjectInputStream ois =
            new ObjectInputStream(new FileInputStream("student.ser"));

        Student s = (Student) ois.readObject();
        System.out.println(s.id + " " + s.name);
        ois.close();
    }
}

6. File Operations (Create, Delete, Rename)

Create File

File file = new File("newfile.txt");
file.createNewFile();

Delete File

file.delete();

Rename File

File oldFile = new File("old.txt");
File newFile = new File("new.txt");
oldFile.renameTo(newFile);

Create Directory

File dir = new File("MyFolder");
dir.mkdir();

Example:

java

import java.io.*;

// Serializable class
class Employee implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int id;
    private transient String password;  // Won't be serialized
    
    public Employee(String name, int id, String password) {
        this.name = name;
        this.id = id;
        this.password = password;
    }
    
    @Override
    public String toString() {
        return "Employee{name='" + name + "', id=" + id + "}";
    }
}

public class FileIODemo {
    public static void main(String[] args) {
        // Writing to a file
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
            writer.write("Hello, File I/O!");
            writer.newLine();
            writer.write("This is line 2");
            System.out.println("File written successfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // Reading from a file
        try (BufferedReader reader = new BufferedReader(new FileReader("output.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // Serialization
        Employee emp = new Employee("John Doe", 101, "secret123");
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("employee.ser"))) {
            oos.writeObject(emp);
            System.out.println("Object serialized");
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // Deserialization
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("employee.ser"))) {
            Employee deserializedEmp = (Employee) ois.readObject();
            System.out.println("Deserialized: " + deserializedEmp);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        
        // File operations
        File file = new File("test.txt");
        try {
            if (file.createNewFile()) {
                System.out.println("File created: " + file.getName());
            }
            System.out.println("File exists: " + file.exists());
            System.out.println("Absolute path: " + file.getAbsolutePath());
            System.out.println("File size: " + file.length() + " bytes");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥