Loading...

Go Back

Next page
Go Back Course Outline

Java Full Course


File Handling in Java

Java File Handling Guide

Java File Handling

File Class

The File class in Java is part of the java.io package and represents file and directory pathnames. It provides methods to perform various operations on files and directories such as creating, deleting, renaming, checking existence, and retrieving file attributes.

Key methods of the File class:

  • createNewFile() - Creates a new empty file
  • delete() - Deletes a file or directory
  • exists() - Tests whether the file exists
  • getName() - Returns the name of the file
  • getAbsolutePath() - Returns the absolute pathname
  • isDirectory() - Tests whether it's a directory
  • length() - Returns the file size in bytes

File Class Example

import java.io.File;

public class FileExample {
    public static void main(String[] args) {
        // Create a File object
        File file = new File("example.txt");
        
        try {
            // Create a new file
            boolean created = file.createNewFile();
            System.out.println("File created: " + created);
            
            // Check file existence
            System.out.println("File exists: " + file.exists());
            
            // Get file properties
            System.out.println("File name: " + file.getName());
            System.out.println("Absolute path: " + file.getAbsolutePath());
            System.out.println("Is directory: " + file.isDirectory());
            System.out.println("Is file: " + file.isFile());
            System.out.println("File size: " + file.length() + " bytes");
            
            // Delete the file
            boolean deleted = file.delete();
            System.out.println("File deleted: " + deleted);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

File created: true
File exists: true
File name: example.txt
Absolute path: /path/to/example.txt
Is directory: false
Is file: true
File size: 0 bytes
File deleted: true

Reading from and Writing to Files

Java provides several classes for reading from and writing to files. The most commonly used are:

FileReader and FileWriter

FileReader reads characters from a file, while FileWriter writes characters to a file. These are best for simple text file operations.

Example: FileReader and FileWriter

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

public class FileReadWrite {
    public static void main(String[] args) {
        String fileName = "sample.txt";
        
        // Writing to a file
        try (FileWriter writer = new FileWriter(fileName)) {
            writer.write("Hello, Java File Handling!\n");
            writer.write("This is a simple example.");
            System.out.println("Data written to file successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // Reading from a file
        try (FileReader reader = new FileReader(fileName)) {
            System.out.println("\nReading file:");
            int character;
            while ((character = reader.read()) != -1) {
                System.out.print((char) character);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

Data written to file successfully.

Reading file:
Hello, Java File Handling!
This is a simple example.

BufferedReader and BufferedWriter

BufferedReader and BufferedWriter provide buffering for character input/output streams, improving performance for file operations. They are particularly efficient for reading text files line by line.

Example: BufferedReader and BufferedWriter

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

public class BufferedReadWrite {
    public static void main(String[] args) {
        String inputFile = "input.txt";
        String outputFile = "output.txt";
        
        // Create input file
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(inputFile))) {
            writer.write("First line\n");
            writer.write("Second line\n");
            writer.write("Third line\n");
            System.out.println("Input file created.");
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // Process file
        try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
             BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
            
            String line;
            int lineNumber = 1;
            
            System.out.println("\nProcessing file...");
            while ((line = reader.readLine()) != null) {
                String processedLine = "Line " + lineNumber + ": " + line;
                writer.write(processedLine);
                writer.newLine();
                System.out.println(processedLine);
                lineNumber++;
            }
            
            System.out.println("File processing complete.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

Input file created.

Processing file...
Line 1: First line
Line 2: Second line
Line 3: Third line
File processing complete.

Scanner for File Input

The Scanner class provides a simple way to read and parse text from files. It's particularly useful for reading structured data like CSV files or configuration files.

Example: Scanner for File Input

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        String fileName = "data.csv";
        
        // Create sample CSV file
        try (java.io.PrintWriter writer = new java.io.PrintWriter(fileName)) {
            writer.println("John,Doe,35,Software Engineer");
            writer.println("Jane,Smith,28,Data Scientist");
            writer.println("Bob,Johnson,42,Project Manager");
            System.out.println("CSV file created.");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        
        // Read and parse CSV file
        try (Scanner scanner = new Scanner(new File(fileName))) {
            System.out.println("\nReading CSV file:");
            
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                String[] data = line.split(",");
                
                System.out.println("First Name: " + data[0]);
                System.out.println("Last Name: " + data[1]);
                System.out.println("Age: " + data[2]);
                System.out.println("Position: " + data[3]);
                System.out.println("----------------------");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Output:

CSV file created.

Reading CSV file:
First Name: John
Last Name: Doe
Age: 35
Position: Software Engineer
----------------------
First Name: Jane
Last Name: Smith
Age: 28
Position: Data Scientist
----------------------
First Name: Bob
Last Name: Johnson
Age: 42
Position: Project Manager
----------------------

Serialization and Deserialization

Serialization is the process of converting an object's state into a byte stream, and deserialization is the process of reconstructing the object from the byte stream. This is useful for saving object state to a file or sending objects over a network.

Key concepts:

  • Implement the Serializable interface to make a class serializable
  • Use transient keyword to exclude fields from serialization
  • Use serialVersionUID for version control

Example: Serialization and Deserialization

import java.io.*;

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

public class SerializationDemo {
    public static void main(String[] args) {
        String fileName = "employee.ser";
        Employee emp = new Employee("John Doe", 35, "secret123");
        
        // Serialization
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName))) {
            oos.writeObject(emp);
            System.out.println("Employee object serialized successfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // Deserialization
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName))) {
            Employee deserializedEmp = (Employee) ois.readObject();
            System.out.println("\nEmployee object deserialized:");
            System.out.println(deserializedEmp);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Output:

Employee object serialized successfully

Employee object deserialized:
Employee [name=John Doe, age=35, password=null]

ObjectInputStream & ObjectOutputStream

The ObjectInputStream and ObjectOutputStream classes are used for serializing and deserializing objects. They provide methods for reading and writing objects and primitive data types.

Example: ObjectInputStream & ObjectOutputStream

import java.io.*;

class Product implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private double price;
    
    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }
    
    @Override
    public String toString() {
        return "Product [name=" + name + ", price=$" + price + "]";
    }
}

public class ObjectStreamsDemo {
    public static void main(String[] args) {
        String fileName = "products.dat";
        Product[] products = {
            new Product("Laptop", 999.99),
            new Product("Phone", 699.99),
            new Product("Tablet", 399.99)
        };
        
        // Writing objects to file
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName))) {
            oos.writeInt(products.length); // Write count
            for (Product p : products) {
                oos.writeObject(p);
            }
            System.out.println("Products written to file.");
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // Reading objects from file
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName))) {
            int count = ois.readInt();
            Product[] loadedProducts = new Product[count];
            
            for (int i = 0; i < count; i++) {
                loadedProducts[i] = (Product) ois.readObject();
            }
            
            System.out.println("\nProducts read from file:");
            for (Product p : loadedProducts) {
                System.out.println(p);
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Output:

Products written to file.

Products read from file:
Product [name=Laptop, price=$999.99]
Product [name=Phone, price=$699.99]
Product [name=Tablet, price=$399.99]
Go Back

Next page