SrcForge

Lesson 56

Java File I/O (NIO)

Java NIO (New Input/Output) is a modern API from the java.nio and java.nio.file packages that provides faster, more flexible, and non-blocking file and directory handling compared to traditional Java I/O.

Java Track

Save progress as you learn.

61 lessons

Lesson content

Java NIO (New Input/Output) is a modern API for working with files, directories, and data streams efficiently. It provides faster and more flexible file handling compared to traditional Java I/O by using classes from the java.nio and java.nio.file packages.

What is Java NIO?

Java NIO (New Input/Output) was introduced to improve file handling and data processing in Java applications. Unlike traditional Java I/O, NIO offers better performance, non-blocking operations, simplified file and directory management, and efficient handling of large files.

Key Terms

  • NIO (New Input/Output): A Java API used for efficient file and data operations.
  • Path: Represents the location of a file or directory.
  • Files: A utility class used to create, read, write, copy, move, and delete files.
  • Directory: A folder that contains files and subdirectories.
  • Non-Blocking I/O: An I/O operation that allows a program to continue execution without waiting for the operation to complete.
  • Path Interface: Represents a file system path in Java.

Why Use Java NIO?

  • Improved performance
  • Easier file manipulation
  • Better support for large files
  • Cleaner and more readable code
  • Built-in support for file operations

Main Classes in Java NIO

ClassDescription
PathRepresents a file or directory path
PathsUsed to create Path objects (older approach)
FilesProvides methods for file operations
FileSystemsAccesses the file system
StandardCopyOptionDefines options for file copy and move operations

Working with Paths in Java NIO

A Path object represents the location of a file or directory.

Example: Path

import java.nio.file.Path;

public class PathExample {
    public static void main(String[] args) {
        Path path = Path.of("example.txt");
        System.out.println(path);
    }
}

Output

example.txt

Creating a File Using NIO

The Files.createFile() method creates a new file.

import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;

public class CreateFileExample {
    public static void main(String[] args) {
        try {
            Path path = Path.of("sample.txt");
            Files.createFile(path);
            System.out.println("File created successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output

File created successfully.

Writing Data to a File

The Files.writeString() method writes text directly to a file.

import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;

public class WriteFileExample {
    public static void main(String[] args) {
        try {
            Path path = Path.of("sample.txt");

            Files.writeString(path,
                    "Welcome to Java NIO File Handling");

            System.out.println("Data written successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output

Data written successfully.

File Content

Welcome to Java NIO File Handling

Reading Data from a File

The Files.readString() method reads the entire file content as a string.

import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;

public class ReadFileExample {
    public static void main(String[] args) {
        try {
            Path path = Path.of("sample.txt");

            String content = Files.readString(path);

            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output

Welcome to Java NIO File Handling

Creating a Directory

The Files.createDirectory() method creates a new directory.

import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;

public class CreateDirectoryExample {
    public static void main(String[] args) {
        try {
            Path path = Path.of("MyFolder");

            Files.createDirectory(path);

            System.out.println("Directory created successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output

Directory created successfully.

Copying a File

The Files.copy() method copies a file from one location to another.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.io.IOException;

public class CopyFileExample {
    public static void main(String[] args) {
        try {
            Path source = Path.of("sample.txt");
            Path destination = Path.of("backup.txt");

            Files.copy(source, destination,
                    StandardCopyOption.REPLACE_EXISTING);

            System.out.println("File copied successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Moving a File

The Files.move() method moves or renames a file.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.io.IOException;

public class MoveFileExample {
    public static void main(String[] args) {
        try {
            Path source = Path.of("sample.txt");
            Path destination = Path.of("NewFolder/sample.txt");

            Files.move(source, destination,
                    StandardCopyOption.REPLACE_EXISTING);

            System.out.println("File moved successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Deleting a File

The Files.delete() method removes a file.

import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;

public class DeleteFileExample {
    public static void main(String[] args) {
        try {
            Path path = Path.of("sample.txt");

            Files.delete(path);

            System.out.println("File deleted successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Checking if a File Exists

The Files.exists() method checks whether a file or directory exists.

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

public class FileExistsExample {
    public static void main(String[] args) {
        Path path = Path.of("sample.txt");

        if (Files.exists(path)) {
            System.out.println("File exists.");
        } else {
            System.out.println("File does not exist.");
        }
    }
}

Common Methods in the Files Class

MethodDescription
createFile()Creates a file
createDirectory()Creates a directory
writeString()Writes text to a file
readString()Reads text from a file
copy()Copies a file
move()Moves or renames a file
delete()Deletes a file
exists()Checks if a file exists
size()Returns file size
readAllLines()Reads all lines from a file

Java NIO vs Traditional Java I/O

FeatureJava I/OJava NIO
API Packagejava.iojava.nio
PerformanceGoodBetter
File HandlingMore codeLess code
Large FilesLess efficientMore efficient
Non-Blocking SupportNoYes
Path SupportLimitedBuilt-in

Advantages of Java NIO

  • Better Performance — efficient for handling large files and data streams.
  • Simplified File Operations — most file tasks can be completed with a single method call.
  • Non-Blocking Support — allows applications to perform multiple tasks simultaneously.
  • Cleaner Code — requires less boilerplate code than traditional I/O.
  • Improved Scalability — suitable for enterprise and high-performance applications.

Best Practices

  • Use Path instead of File — prefer Path objects for modern Java applications.
  • Handle exceptions properly — always wrap file operations inside try-catch blocks.
  • Check file existence — use Files.exists() before performing operations.
  • Close resources when needed — use try-with-resources for streams and channels.
  • Use NIO for new projects — prefer java.nio.file classes over legacy java.io classes whenever possible.

FAQ

1. What is Java NIO?

Java NIO (New Input/Output) is a modern API used for efficient file, directory, and data handling operations.

2. What is the difference between Java I/O and Java NIO?

Java NIO provides better performance, non-blocking operations, and simpler file handling compared to traditional Java I/O.

3. Which class is commonly used for file operations in Java NIO?

The Files class is commonly used for creating, reading, writing, copying, moving, and deleting files.

Java NIO (java.nio.file) offers better performance and non-blocking I/O over traditional java.io.
Path represents a file or directory location; Files provides static utility methods for file operations.
Files.writeString() and Files.readString() simplify writing and reading text files in one call.
Files.copy() and Files.move() use StandardCopyOption.REPLACE_EXISTING to control overwrite behavior.
Files.exists() checks file presence before performing operations, avoiding exceptions.
Prefer java.nio.file classes over legacy java.io classes for new Java projects.

Where Java is used

Java in real-world development

Path

Represents the location of a file or directory; created using Path.of().

Files

Utility class providing static methods to create, read, write, copy, move, and delete files.

Files.writeString()

Writes text directly to a file in a single method call.

Files.readString()

Reads the entire content of a file as a String.

Files.copy() / Files.move()

Copies or moves files between locations, optionally replacing existing files with StandardCopyOption.REPLACE_EXISTING.

Files.exists()

Checks whether a file or directory exists before performing further operations.

Prev: InputStream and OutputStreamBack to hub