Java Program to write data into a File using NIO.
Objective
Write a Java program to write a String of data to a file using Java NIO (New I/O) Channels.
Algorithm / Approach
- Import
java.nio.*andjava.nio.channels.*. - Ask the user for a file name and the string data they want to save.
- Open a
FileOutputStreamand extract itsWritableByteChannel. - Convert the user's String into a byte array (
data.getBytes()). - Allocate a
ByteBufferof the appropriate size andput()the bytes into it. - Call
buff.rewind()to reset the buffer's position pointer to 0. - Write the buffer to the channel using
chan.write(buff).
WriteFile.java
import java.nio.*;
import java.io.*;
import java.util.*;
import java.nio.channels.*;
class WriteFile{
public static void main(String[] a)
throws Exception {
Scanner s=new Scanner(System.in);
System.out.print("Enter File: ");
String file=s.nextLine();
FileOutputStream fout = null;
WritableByteChannel chan = null;
ByteBuffer buff = null;
System.out.print("Enter Data: ");
String data=s.nextLine();
try {
fout = new FileOutputStream(file);
chan = fout.getChannel();
byte[] b = data.getBytes();
int size = b.length;
buff = ByteBuffer.allocate(size);
buff.put(b);
buff.rewind();
chan.write(buff);
System.out.print("Written Successfully");
}
catch(Exception e) {
System.out.print(e);
}
finally{
try {
fout.close();
chan.close();
}
catch(Exception e) {
System.out.print(e);
}
}
}
}
Expected Output
Enter File: Alok.txt Enter Data: Java Prowess is one of the largest application for java Written Successfully
Explanation of the Program
- Java NIO (New I/O) was introduced in Java 1.4 to provide high-speed, scalable I/O operations.
- Unlike standard I/O (which reads/writes data one byte or character at a time using Streams), NIO uses Blocks of data. You put data into a
Buffer, and send that entire Buffer through aChannel. - The
rewind()step is critical: when you fill the buffer, the internal pointer moves to the end. You must "rewind" it back to the start so the Channel knows to read the data from the beginning.
Complexity
Time Complexity
O(n) - Where n is the number of bytes written.
Space Complexity
O(n) - For allocating the ByteBuffer in memory.