Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Advanced File IO in Java 8

Overview

Java 8 introduced several enhancements to the file I/O (NIO) API, making it easier to work with files, directories, and file systems. The java.nio.file package provides a comprehensive set of tools for performing advanced file I/O operations.

Reading and Writing Files

The Files class provides various methods to read and write files efficiently.

Example: Reading a File

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;

public class FileReadExample {
    public static void main(String[] args) throws IOException {
        List lines = Files.readAllLines(Paths.get("example.txt"));
        lines.forEach(System.out::println);
    }
}

Example: Writing to a File

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class FileWriteExample {
    public static void main(String[] args) throws IOException {
        List lines = Arrays.asList("Line 1", "Line 2", "Line 3");
        Files.write(Paths.get("example.txt"), lines);
    }
}

Walking a File Tree

The Files.walkFileTree method allows you to traverse a directory tree, visiting each file and directory.

Example: Walking a File Tree

import java.nio.file.*;
import java.io.IOException;
import java.nio.file.attribute.BasicFileAttributes;

public class FileTreeWalkExample {
    public static void main(String[] args) throws IOException {
        Path startPath = Paths.get(".");
        Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                System.out.println("Visited file: " + file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                System.err.println("Visit failed for file: " + file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                System.out.println("About to visit directory: " + dir);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                System.out.println("Just visited directory: " + dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

Working with File Attributes

You can read and modify file attributes using the Files class.

Example: Reading File Attributes

import java.nio.file.*;
import java.io.IOException;
import java.nio.file.attribute.BasicFileAttributes;

public class FileAttributesExample {
    public static void main(String[] args) throws IOException {
        Path filePath = Paths.get("example.txt");
        BasicFileAttributes attrs = Files.readAttributes(filePath, BasicFileAttributes.class);

        System.out.println("Creation Time: " + attrs.creationTime());
        System.out.println("Last Modified Time: " + attrs.lastModifiedTime());
        System.out.println("Size: " + attrs.size());
    }
}

Example: Setting File Attributes

import java.nio.file.*;
import java.io.IOException;
import java.nio.file.attribute.FileTime;

public class SetFileAttributesExample {
    public static void main(String[] args) throws IOException {
        Path filePath = Paths.get("example.txt");
        FileTime lastModifiedTime = FileTime.fromMillis(System.currentTimeMillis());

        Files.setLastModifiedTime(filePath, lastModifiedTime);
        System.out.println("Updated Last Modified Time: " + Files.getLastModifiedTime(filePath));
    }
}

Monitoring File Changes

The WatchService API allows you to monitor changes to files and directories.

Example: Monitoring File Changes

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

public class WatchServiceExample {
    public static void main(String[] args) throws IOException, InterruptedException {
        WatchService watchService = FileSystems.getDefault().newWatchService();
        Path path = Paths.get(".");

        path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);

        System.out.println("Watching directory: " + path);

        WatchKey key;
        while ((key = watchService.take()) != null) {
            for (WatchEvent<?> event : key.pollEvents()) {
                System.out.println("Event kind: " + event.kind() + ". File affected: " + event.context() + ".");
            }
            key.reset();
        }
    }
}

Using File Channels for Efficient I/O

File channels provide a way to perform efficient I/O operations using buffers.

Example: Using File Channels

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FileChannelExample {
    public static void main(String[] args) throws IOException {
        Path filePath = Paths.get("example.txt");

        // Writing to a file using FileChannel
        try (FileChannel fileChannel = FileChannel.open(filePath, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
            ByteBuffer buffer = ByteBuffer.allocate(64);
            buffer.put("Hello, FileChannel!".getBytes());
            buffer.flip();
            fileChannel.write(buffer);
        }

        // Reading from a file using FileChannel
        try (FileChannel fileChannel = FileChannel.open(filePath, StandardOpenOption.READ)) {
            ByteBuffer buffer = ByteBuffer.allocate(64);
            fileChannel.read(buffer);
            buffer.flip();
            System.out.println(new String(buffer.array(), 0, buffer.limit()));
        }
    }
}

Conclusion

Java 8 introduced several enhancements to the file I/O API, providing more efficient and flexible ways to work with files and directories. By leveraging these advanced file I/O features, developers can perform complex file operations with ease and efficiency.