Sunday 16 June 2019

NIO: Exploring OpenOption


OpenOption is used by FileChannel and specifies how to open or create a file.

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

public interface OpenOption {
}

LinkOption and StandardOpenOption enums implement 'OpenOption' interface.

Below table summarizes the constants provided by StandardOpenOption enum.
Constant
Description
READ
Open for read access.
WRITE
Open for write access.
APPEND
If the file is opened for WRITE access then bytes will be written to the end of the file rather than the beginning.

If the file is opened for write access by other programs, then it is file system specific if writing to the end of the file is atomic.
TRUNCATE_EXISTING
If the file already exists and it is opened for WRITE
access, then its length is truncated to 0. This option is ignored if the file is opened only for READ access.
CREATE
Create a new file if it does not exist. This option is ignored if the CREATE_NEW option is also set.
CREATE_NEW
Create a new file, fails if the file already exists.
DELETE_ON_CLOSE
Delete on close.
SPARSE
Sparse File. A sparse file is a type of computer file that attempts to use file system space more efficiently when the file itself is partially empty.
SYNC
Requires that every update to the file's content or metadata be written synchronously to the underlying storage device.
DSYNC
Requires that every update to the file's content be written synchronously to the underlying storage device.

Below table summarizes the enum constants provided by LinkOption.

Constant
Description
NOFOLLOW_LINKS
Do not follow symbolic links.

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