What is FileChannel in Java?

FileChannel is a part of the Java NIO (New Input/Output) package that allows for efficient reading and writing of data to files. It provides methods for manipulating files in an asynchronous and scalable manner. With FileChannel, developers can perform operations like reading, writing, truncating, and mapping file regions into memory.

A FileChannel is associated with a file descriptor and can be obtained from a FileInputStream or FileOutputStream. It provides a more flexible and powerful way to handle file operations compared to the traditional approach using FileInputStream and FileOutputStream.

        import java.io.*;
        import java.nio.channels.FileChannel;

        public class FileChannelExample {
            public static void main(String[] args) {
                try {
                    // Create a FileInputStream to read a file
                    FileInputStream fis = new FileInputStream("example.txt");
                    FileChannel fileChannel = fis.getChannel();

                    // Allocate a buffer
                    ByteBuffer buffer = ByteBuffer.allocate(1024);

                    // Read data into the buffer
                    int bytesRead = fileChannel.read(buffer);
                    System.out.println("Bytes read: " + bytesRead);

                    // Close the channel and stream
                    fileChannel.close();
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    

FileChannel Java NIO file operations asynchronous file handling