Java File I/O and Collections Framework Essentials

Java File Operations with RandomAccessFile

The RandomAccessFile class in Java is part of the java.io package and provides functionality for reading from and writing to a file at any specified position. Unlike sequential input/output streams, RandomAccessFile allows non-sequential access to file contents, making it suitable for tasks like updating specific parts of a file or working with structured data records.

RandomAccessFile Example: Reading, Writing, and Appending

This example demonstrates how to use RandomAccessFile to perform various operations on a text file named “data.txt”. It covers creating the file, writing initial data, moving the file pointer using seek(), reading data, and appending new content.

import java.io.*;

public class RandomAccessFileExample {
    public static void main(String[] args) {
        try {
            // Create a RandomAccessFile object with read-write mode ("rw")
            RandomAccessFile file = new RandomAccessFile("data.txt", "rw");

            // Write initial data to the file using writeUTF()
            String data1 = "Hello";
            String data2 = "World";
            file.writeUTF(data1);
            file.writeUTF(data2);

            // Move the file pointer to the beginning of the file (position 0)
            file.seek(0);

            // Read data from the file
            String readData1 = file.readUTF();
            String readData2 = file.readUTF();
            System.out.println("Data read from file:");
            System.out.println(readData1);
            System.out.println(readData2);

            // Move the file pointer to the end of the file
            file.seek(file.length());

            // Append new data to the file
            String newData = "Java!";
            file.writeUTF(newData);

            // Move the file pointer back to the beginning to read all content
            file.seek(0);

            // Read data from the file again after appending
            readData1 = file.readUTF();
            readData2 = file.readUTF();
            String readData3 = file.readUTF();
            System.out.println("Data read from file after appending:");
            System.out.println(readData1);
            System.out.println(readData2);
            System.out.println(readData3);

            // Close the file to release resources
            file.close();
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Java Collections Framework Fundamentals

The Java Collections Framework (JCF) provides a set of interfaces and classes to represent and manipulate collections of objects. It offers a unified architecture for storing and processing groups of data, improving program efficiency and reusability. Key interfaces include:

  • List: An ordered collection (also known as a sequence). Lists can contain duplicate elements.
  • Set: A collection that does not contain duplicate elements.
  • Map: An object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value.

List Interface: ArrayList Example

The ArrayList class implements the List interface and uses a dynamic array to store elements. It allows for fast random access but can be slower for insertions and deletions in the middle of the list.

ListExample.java Code

package collections;

import java.util.ArrayList;

public class ListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");
        // Displaying the elements of the list
        System.out.println("List Example:");
        for (String fruit : list) {
            System.out.println(fruit);
        }
    }
}

Set Interface: HashSet Example

The HashSet class implements the Set interface and stores elements in a hash table. It does not maintain insertion order and does not allow duplicate elements. Adding a duplicate element has no effect.

SetExample.java Code

package collections;

import java.util.HashSet;

public class SetExample {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();
        set.add("Apple");
        set.add("Banana");
        set.add("Orange");
        set.add("Apple"); // This won't be added since sets do not allow duplicates
        // Displaying the elements of the set
        System.out.println("Set Example:");
        for (String fruit : set) {
            System.out.println(fruit);
        }
    }
}

Map Interface: HashMap Example

The HashMap class implements the Map interface and stores key-value pairs. It provides efficient storage and retrieval of elements based on their keys. Keys must be unique, but values can be duplicated.

MapExample.java Code

package collections;

import java.util.HashMap;
import java.util.Map; // Required for Map.Entry

public class MapExample {
    public static void main(String[] args) {
        HashMap<Integer, String> map = new HashMap<>();
        map.put(1, "Apple");
        map.put(2, "Banana");
        map.put(3, "Orange");
        // Displaying the key-value pairs of the map
        System.out.println("Map Example:");
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Running All Collections Examples: CollectionsDemo

The CollectionsDemo class serves as a simple entry point to execute the main methods of the ListExample, SetExample, and MapExample classes sequentially, demonstrating the output of each collection type.

CollectionsDemo.java Code

package collections;

public class CollectionsDemo {
    public static void main(String[] args) {
        ListExample.main(args);
        SetExample.main(args);
        MapExample.main(args);
    }
}

image