FileChannel Write Example

This program demonstrates writing to a file using FileChannel.

Problem Statement

Write a Java program that writes data into a file using FileChannel and ByteBuffer.

Source Code

1 import java.io.*;
2 import java.nio.*;
3 import java.nio.channels.*;
4 import java.nio.file.*;
5 public class FileChannelWriteExample {
6 public static void main(String[] args) throws Exception {
7 System.out.println("Eduinq FileChannel Write Example");
8 FileChannel channel=FileChannel.open(Paths.get("output.txt"),StandardOpenOption.WRITE,StandardOpenOption.CREATE);
9 ByteBuffer buffer=ByteBuffer.wrap("Eduinq FileChannel Write".getBytes());
10 channel.write(buffer);
11 channel.close();
12 System.out.println("Eduinq Data Written Successfully");
13 }
14 }

Program Output

					Eduinq FileChannel Write Example
Eduinq Data Written Successfully
				

Explanation

Uses FileChannel.write() with ByteBuffer. - Writes string into file. - Exception handling ensures safe operations. - In enterprise systems, FileChannel supports efficient writing. Conclusion: Shows writing with FileChannel.

Quick Links to Explore