EZ

Eduzan

Learning Hub

Eduzan
Eduzan / Java

File Handling

Java’s File class represents the pathname of a file or directory. Since file systems vary across platforms, using a simple string is not enough to handle file or directory names. The File class provides various methods to work with pathnames, such as deleting or renaming files, creating new directories, listing directory contents, and checking file or directory properties.

Key Features of the File Class

The File class acts as an abstract representation of file and directory pathnames. The pathname can either be absolute or relative, and you can obtain the parent directory by calling the getParent() method. An instance of the File class is immutable; once created, the pathname it represents doesn’t change.

The file system can impose certain access restrictions like read, write, or execute permissions on files or directories, referred to as access permissions.

How to Create a File Object

File object is created by passing a string representing a file or directory name. You can use either a string or another File object. For example:

File file = new File("/home/user/docs/myfile.txt");

This creates a File object representing the myfile.txt file in the /home/user/docs directory.

Fields in the File Class

File Handling
FieldTypeDescription
pathSeparatorStringString used to separate paths in a file system.
pathSeparatorCharcharCharacter used to separate paths in a file system.
separatorStringDefault name separator character, represented as a string.
separatorCharcharDefault name separator character.

Constructors of the File Class

Methods of the File Class

1. File(File parent, String child): Creates a File instance from a parent directory and a child pathname.
2. File(String pathname): Creates a File instance from a string pathname.
3. File(String parent, String child): Creates a File instance from a parent directory string and a child pathname.
4. File(URI uri): Creates a File instance from a URI object.

File Handling
MethodDescriptionReturn Type
canExecute()Checks if the file can be executed.boolean
canRead()Checks if the file can be read.boolean
canWrite()Checks if the file can be written to.boolean
compareTo(File pathname)Compares two pathnames lexicographically.int
createNewFile()Atomically creates a new empty file.boolean
delete()Deletes the file or directory.boolean
exists()Checks if the file or directory exists.boolean
getAbsolutePath()Returns the absolute pathname string.String
list()Returns an array of names of files and directories.String[]
getFreeSpace()Returns the number of unallocated bytes in the partition.long
getName()Returns the name of the file or directory.String
isDirectory()Checks if the pathname is a directory.boolean
isFile()Checks if the pathname is a regular file.boolean
isHidden()Checks if the file is hidden.boolean
length()Returns the length of the file in bytes.long
mkdir()Creates a new directory.boolean
renameTo(File dest)Renames the file or directory.boolean
toString()Returns the string representation of the pathname.String
toURI()Returns a URI representing the pathname.URI
import java.util.*;
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Example 1: Check if a File or Directory Exists

This program takes a filename or directory name as input, then checks if the file or directory exists and displays its properties.

import java.io.File;

class FileProperties {
    public static void main(String[] args) {
        String filename = args[0];
        File file = new File(filename);

        System.out.println("File Name: " + file.getName());
        System.out.println("Path: " + file.getPath());
        System.out.println("Absolute Path: " + file.getAbsolutePath());
        System.out.println("Parent: " + file.getParent());
        System.out.println("Exists: " + file.exists());

        if (file.exists()) {
            System.out.println("Writable: " + file.canWrite());
            System.out.println("Readable: " + file.canRead());
            System.out.println("Is Directory: " + file.isDirectory());
            System.out.println("File Size (bytes): " + file.length());
        }
    }
}

Output:

File Name: file.txt
Path: file.txt
Absolute Path: /home/user/file.txt
Parent: null
Exists: true
Writable: true
Readable: true
Is Directory: false
File Size (bytes): 100

Example 2: Display Directory Contents

This program accepts a directory path from the user and lists its contents.

import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

class DirectoryContents {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Enter directory path:");
        String dirPath = br.readLine();

        File dir = new File(dirPath);

        if (dir.exists() && dir.isDirectory()) {
            String[] contents = dir.list();
            System.out.println("Contents of " + dirPath + ":");

            for (String item : contents) {
                File f = new File(dirPath, item);
                if (f.isFile()) {
                    System.out.println(item + " (File)");
                } else if (f.isDirectory()) {
                    System.out.println(item + " (Directory)");
                }
            }
        } else {
            System.out.println("Directory not found.");
        }
    }
}

Output:

Enter directory path:
/home/user/docs
Contents of /home/user/docs:
file1.txt (File)
file2.txt (File)
subfolder (Directory)
End of lesson.