Writing a file using Channel and Buffer

suggest change

To write data to a file using Channel we need to have the following steps:

  1. First, we need to get an object of FileOutputStream
  2. Acquire FileChannel calling the getChannel() method from the FileOutputStream
  3. Create a ByteBuffer and then fill it with data
  4. Then we have to call the flip() method of the ByteBuffer and pass it as an argument of the write() method of the FileChannel
  5. Once we are done writing, we have to close the resource
import java.io.*;
import java.nio.*;
public class FileChannelWrite {

 public static void main(String[] args) {

  File outputFile = new File("hello.txt");
  String text = "I love Bangladesh.";

  try {
   FileOutputStream fos = new FileOutputStream(outputFile);
   FileChannel fileChannel = fos.getChannel();
   byte[] bytes = text.getBytes();
   ByteBuffer buffer = ByteBuffer.wrap(bytes);
   fileChannel.write(buffer);
   fileChannel.close();
  } catch (java.io.IOException e) {
   e.printStackTrace();
  }
 }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


File I/O:
* Writing a file using Channel and Buffer

Table Of Contents
7 File I/O
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap