Thursday, 13 June 2019

NIO: FileChannel.open method

'FileChannel.open' method is used to Open or create a file, and return a file channel to access the file.

Signature
public static FileChannel open(Path path, OpenOption... options)

OpenOption represents an object that configures how to open or create a file.

Example
FileChannel channel = FileChannel.open(Paths.get(FILE_PATH), CREATE, WRITE);

Test.java
package com.sample.app;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.WRITE;

public class Test {

 private static final String FILE_PATH = "/Users/krishna/Documents/demo.txt";

 public static void main(String... args) throws IOException {
  FileChannel channel = FileChannel.open(Paths.get(FILE_PATH), CREATE, WRITE);

  ByteBuffer buffer = ByteBuffer.allocate(2048);

  buffer.put("Welcome to NIO Programming".getBytes());

  buffer.flip();
  channel.write(buffer);

  channel.close();

 }
}


Run Test.java and open demo.txt file, you can see "Welcome to NIO Programming".

$cat demo.txt
Welcome to NIO Programming

Previous                                                 Next                                                 Home

No comments:

Post a Comment