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 public class FileChannelWriteExample {
5 public static void main(String[] args) {
6 System.out.println("Eduinq FileChannel Write Example");
7 try(FileOutputStream fos=new FileOutputStream("output.txt");
8 FileChannel fc=fos.getChannel()) {
9 ByteBuffer buffer=ByteBuffer.wrap("Eduinq FileChannel Write".getBytes());
10 fc.write(buffer);
11 System.out.println("Eduinq Data Written Successfully");
12 } catch(Exception e){ System.out.println("Eduinq Exception: "+e.getMessage()); }
13 }
14 }

Program Output

					Eduinq FileChannel Write Example
Eduinq Data Written Successfully
				

Explanation

Uses FileChannel with ByteBuffer. - Efficient writing with NIO. - Exception handling ensures safe operations. - In enterprise systems, FileChannel improves throughput. Conclusion: Shows writing with FileChannel.

Quick Links to Explore