Java IO & NIO - Files.newByteChannel() Examples

Code Snippets Java IO & NIO Java 


Class:

java.nio.file.Files

java.lang.Objectjava.lang.Objectjava.nio.file.Filesjava.nio.file.FilesLogicBig

Methods:

public static SeekableByteChannel newByteChannel(Path path,
                                                 OpenOption... options)
                                          throws IOException

public static SeekableByteChannel newByteChannel(Path path,
                                                 Set<? extends OpenOption> options,
                                                 FileAttribute<?>... attrs)
                                          throws IOException

Opens or creates a file, returning a seekable byte channel to access the file.

Parameters:
path - the path to the file to open or create
options - options specifying how the file is opened
attrs - an optional list of file attributes to set atomically when creating the file
Returns:
a new seekable byte channel




Examples


package com.logicbig.example.files;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class NewByteChannelExample {

public static void main(String... args) throws IOException {
Path path = Files.createTempFile("test-file", ".txt");
try (SeekableByteChannel channel = Files.newByteChannel(path, StandardOpenOption.READ,
StandardOpenOption.WRITE)) {
ByteBuffer byteBuffer = ByteBuffer.wrap("test string".getBytes());
int b = channel.write(byteBuffer);
System.out.println("bytes written: " + b);
channel.position(0);
ByteBuffer byteBuffer2 = ByteBuffer.allocate(b);
channel.read(byteBuffer2);
System.out.println(new String(byteBuffer2.array()));
}
}
}

Output

bytes written: 11
test string




See Also