Opens or creates a file, returning a seekable byte channel to access the file.
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