import java.io.RandomAccessFile; import java.nio.channels.FileChannel; public class Main { public static void main(String[] args) throws Exception { RandomAccessFile file = new RandomAccessFile("example.txt", "rw"); FileChannel channel = file.getChannel(); // Use the channel object to perform operations on the file } }
import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class Main { public static void main(String[] args) throws IOException { RandomAccessFile file = new RandomAccessFile("example.txt", "rw"); FileChannel channel = file.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); int bytesRead = channel.read(buffer); while (bytesRead != -1) { buffer.flip(); while (buffer.hasRemaining()) { System.out.print((char) buffer.get()); } buffer.clear(); bytesRead = channel.read(buffer); } file.close(); } }In this example, we are reading data from the file "example.txt" using a FileChannel object. We allocate a ByteBuffer object to read data into, and then repeatedly read data from the channel into the buffer until we reach the end of the file. We then print out the data to the console. Package library: java.io, java.nio.