Random- Access Files, Files and Directories

Filter Course


Random- Access Files, Files and Directories

Published by: Dikshya

Published date: 02 Jul 2023

Random- Access Files, Files and Directories

Random-Access Files:

  • Random-access files allow you to read and write data at any position within a file. Unlike sequential access files, which only allow you to read or write data sequentially from the beginning to the end of a file, random-access files provide the flexibility to directly access any part of the file.
  • In Java, the RandomAccessFile class is used to work with random-access files. It provides methods such as seek() to move the file pointer to a specific position and read() and write() methods to perform read and write operations at that position.

Example:

import java.io.RandomAccessFile;

public class RandomAccessFileExample {
    public static void main(String[] args) {
        try {
            RandomAccessFile file = new RandomAccessFile("data.txt", "rw");
            
            // Writing data to the file
            file.writeUTF("Hello");
            file.writeInt(123);
            file.writeDouble(3.14);
            
            // Moving the file pointer to a specific location
            file.seek(0);
            
            // Reading data from the file
            String text = file.readUTF();
            int number = file.readInt();
            double value = file.readDouble();
            
            System.out.println("Text: " + text);
            System.out.println("Number: " + number);
            System.out.println("Value: " + value);
            
            file.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In this example, we create a RandomAccessFile object named file and open it in "rw" mode (read and write). We then write some data to the file using various methods like writeUTF, writeInt, and writeDouble. After that, we move the file pointer to the beginning of the file using seek method. Finally, we read the data back from the file using methods like readUTF, readInt, and readDouble, and display the values on the console.

Files and Directories:

  • In the context of file systems, files and directories are the basic units used to organize and store data.
  • A file is a named collection of data stored on a storage medium. It can contain various types of data, such as text, images, videos, or program executables. Files are identified by their names and are organized within directories.
  • A directory, also known as a folder, is a container for files and other directories. It provides a way to organize and manage files by grouping related files together. Directories can be nested within other directories, forming a hierarchical structure. The top-level directory in a file system is typically called the root directory.
  • In Java, the java.io.File class is commonly used to interact with files and directories. It provides methods to create, delete, rename, and query files and directories. Additionally, the java.nio.file package introduced in Java 7 provides a more modern and flexible API for working with files and directories. It includes classes such as Path and Files for performing various file system operations.

Creating a Directory

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CreateDirectoryExample {
    public static void main(String[] args) {
        try {
            Path directoryPath = Paths.get("mydir");
            Files.createDirectory(directoryPath);
            System.out.println("Directory created successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

This example creates a new directory named "mydir" using the createDirectory method from the Files class.

Creating a File:

import java.io.File;
import java.io.IOException;

public class CreateFileExample {
    public static void main(String[] args) {
        try {
            File file = new File("myfile.txt");
            if (file.createNewFile()) {
                System.out.println("File created successfully.");
            } else {
                System.out.println("File already exists.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
In this example, we create a new file named "myfile.txt" using the createNewFile method from the File class. It returns true if the file is created successfully, or false if the file already exists.