Java IO & NIO Java Java API
java.nio.file.Files
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.
path
options
attrs
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())); } }}
bytes written: 11test string