Files

The Files class is part of the java.nio.file package introduced in Java 7. It contains static methods that operate on files, directories, or other types of files.Files is a utility class and cannot be instantiated.

  • Utility class for file and directory operations.
  • Provides methods to create, delete, copy, move, read, write, and check file attributes.
  • Works with Path objects (from java.nio.file.Path).
  • Offers better exception handling and efficiency compared to older java.io.File.

Commonly Used Methods

Simple Program Using Files Class

Create a simple Java program that creates a new text file, writes some text to it, reads the content back, and then deletes the file.

import java.nio.file.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class SimpleFilesExample {
    public static void main(String[] args) {
        Path filePath = Paths.get("example.txt");
        
        try {
            // Create file
            Files.createFile(filePath);
            System.out.println("File created: " + filePath.toAbsolutePath());
            
            // Write to file
            String content = "Hello, this is a test file.";
            Files.write(filePath, content.getBytes(StandardCharsets.UTF_8));
            System.out.println("Content written to file.");
            
            // Read file content
            String readContent = Files.readString(filePath);
            System.out.println("Read content: " + readContent);
            
            // Delete file
            Files.delete(filePath);
            System.out.println("File deleted.");
            
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

Problem Statement:

You are building a small utility to manage user-uploaded documents in a folder. The program should:

  1. Create a directory named “UserDocs” if it doesn’t exist.
  2. For each uploaded document (simulate by creating a few sample files), create a file inside “UserDocs”.
  3. Copy the file to a backup folder named “BackupDocs”.
  4. List all files in the “UserDocs” folder.
  5. Delete the files older than a certain threshold (e.g., 1 day).
import java.nio.file.*;
import java.nio.file.attribute.FileTime;
import java.io.IOException;
import java.time.*;
import java.util.stream.Stream;

public class UserDocsManager {

    private static final Path USER_DOCS_DIR = Paths.get("UserDocs");
    private static final Path BACKUP_DIR = Paths.get("BackupDocs");

    public static void main(String[] args) {
        try {
            // 1. Create directories if they don't exist
            if (!Files.exists(USER_DOCS_DIR)) {
                Files.createDirectory(USER_DOCS_DIR);
                System.out.println("Created directory: " + USER_DOCS_DIR);
            }
            if (!Files.exists(BACKUP_DIR)) {
                Files.createDirectory(BACKUP_DIR);
                System.out.println("Created directory: " + BACKUP_DIR);
            }

            // 2. Create sample files simulating user documents
            for (int i = 1; i <= 3; i++) {
                Path file = USER_DOCS_DIR.resolve("document" + i + ".txt");
                if (!Files.exists(file)) {
                    Files.writeString(file, "This is the content of document " + i);
                    System.out.println("Created file: " + file.getFileName());
                }
            }

            // 3. Copy files to backup folder
            try (Stream<Path> files = Files.list(USER_DOCS_DIR)) {
                files.forEach(file -> {
                    Path backupFile = BACKUP_DIR.resolve(file.getFileName());
                    try {
                        Files.copy(file, backupFile, StandardCopyOption.REPLACE_EXISTING);
                        System.out.println("Copied " + file.getFileName() + " to backup folder.");
                    } catch (IOException e) {
                        System.err.println("Failed to copy " + file.getFileName() + ": " + e.getMessage());
                    }
                });
            }

            // 4. List all files in UserDocs folder
            System.out.println("\nFiles in " + USER_DOCS_DIR + ":");
            try (Stream<Path> files = Files.list(USER_DOCS_DIR)) {
                files.forEach(file -> System.out.println("- " + file.getFileName()));
            }

            // 5. Delete files older than 1 day
            final Instant cutoff = Instant.now().minus(Duration.ofDays(1));
            try (Stream<Path> files = Files.list(USER_DOCS_DIR)) {
                files.forEach(file -> {
                    try {
                        FileTime lastModified = Files.getLastModifiedTime(file);
                        if (lastModified.toInstant().isBefore(cutoff)) {
                            Files.delete(file);
                            System.out.println("Deleted old file: " + file.getFileName());
                        }
                    } catch (IOException e) {
                        System.err.println("Error checking/deleting " + file.getFileName() + ": " + e.getMessage());
                    }
                });
            }

        } catch (IOException e) {
            System.err.println("IO Error: " + e.getMessage());
        }
    }
}

The Files class, introduced in Java NIO.2 (java.nio.file package), provides a comprehensive and convenient API for file and directory operations. It simplifies common file handling tasks such as creating, deleting, copying, moving files and directories, reading and writing file content, and managing file attributes—all with enhanced flexibility and improved exception handling compared to the legacy java.io classes.

Key features include:

  • Static utility methods for file I/O operations,
  • Support for both synchronous and asynchronous file operations,
  • Integration with Path objects for modern and efficient file path handling,
  • Ability to handle file metadata and permissions easily.

The Files class improves code readability and reliability, making file manipulation straightforward and less error-prone. It is a fundamental part of modern Java file I/O programming.

Scroll to Top