Home Java Files Methods newByteChannel() Java Files newByteChannel() Method Definition In Java, Files.newByteChannel(path, options...) opens a file and returns a SeekableByteChannel. A channel moves bytes through a ByteBuffer and has a position you can change, so you can read the end of a file or overwrite the middle without touching the rest.
With no options it opens for reading. Add WRITE, CREATE, APPEND, and so on for writing. It is the NIO.2 answer to RandomAccessFile.
A static method of the final utility class java.nio.file.Files, available since Java 7. Call it on the class name, as in Files.newByteChannel(...), after import java.nio.file.Files;. You never create a Files object.
Syntax Options as varargs, or as a Set plus attributes:
try (SeekableByteChannel ch = Files.newByteChannel(path)) { // read
ch.position(ch.size() - 5);
ch.read(buffer);
}
Files.newByteChannel(path, EnumSet.of(CREATE_NEW, WRITE)); // Set overload Call What it does ch.read(buf)Read into a ByteBuffer; returns bytes read or -1. ch.write(buf)Write the buffer's remaining bytes. ch.position(n)Move to byte n. ch.truncate(n)Cut the file to n bytes.
Since Java 7. For the default file system the channel is actually a FileChannel, which adds memory mapping and locking.
Library declarations public static SeekableByteChannel newByteChannel(Path path, OpenOption... options) throws IOException
public static SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException Parameters Parameter Description pathThe file to open. optionsREAD, WRITE, APPEND, CREATE, CREATE_NEW, TRUNCATE_EXISTING, and more.attrs(Set overload) Attributes for a newly created file.
Return Value Return Value Description SeekableByteChannelAn open channel at position 0 (or at the end with APPEND).
Important
Throws NoSuchFileException when reading a missing file, FileAlreadyExistsException with CREATE_NEW if the file exists, and IllegalArgumentException for contradictory options such as READ with APPEND. A single read may fill less than the buffer, so check the return value.
Compare with Similar Methods Streams vs channels:
Java Examples 1. Read the last bytes 2. Overwrite in the middle 3. Set overload and truncate Example 1 — Jump to the End of a File Set the position to five bytes before the end and read just those bytes.
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class NewByteChannelTail {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("demo");
Path file = dir.resolve("message.txt");
Files.write(file, "Hello, channel!".getBytes(StandardCharsets.US_ASCII));
try (SeekableByteChannel ch = Files.newByteChannel(file)) {
System.out.println("Size: " + ch.size());
ch.position(ch.size() - 5);
ByteBuffer buf = ByteBuffer.allocate(5);
while (buf.hasRemaining() && ch.read(buf) != -1) {
// keep reading until the buffer is full
}
buf.flip();
System.out.println("Last 5 bytes: " + StandardCharsets.US_ASCII.decode(buf));
}
Files.delete(file);
Files.delete(dir);
}
} Run with java NewByteChannelTail. The output is the same on Windows, macOS, and Linux.
Size: 15
Last 5 bytes: nnel! How It Works Read-only by default. With no options, the channel opens the existing file for reading.Seek, then read. The text has 15 bytes, so position(10) skips Hello, chan and lands on the second n.Fill, then flip. The loop reads until the 5-byte buffer is full; flip() switches the buffer from writing to reading before decoding.Example 2 — Replace One Word Without Rewriting the File Open an existing file with WRITE (no truncation), move to byte 6, and write five new bytes.
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class NewByteChannelOverwrite {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("demo");
Path file = dir.resolve("greet.txt");
Files.write(file, "Hello World".getBytes(StandardCharsets.US_ASCII));
try (SeekableByteChannel ch = Files.newByteChannel(file, StandardOpenOption.WRITE)) {
ch.position(6);
ch.write(ByteBuffer.wrap("Java!".getBytes(StandardCharsets.US_ASCII)));
}
System.out.println(new String(Files.readAllBytes(file), StandardCharsets.US_ASCII));
System.out.println("Size: " + Files.size(file));
Files.delete(file);
Files.delete(dir);
}
} Run with java NewByteChannelOverwrite. The output is the same on Windows, macOS, and Linux.
Hello Java!
Size: 11 How It Works WRITE alone keeps the data. Without TRUNCATE_EXISTING the file is not emptied, so only the bytes you write change.Byte 6 is the W. "Hello " is six bytes (0 to 5), so writing at position 6 replaces World.Same length, same size. Java! is also five bytes, so the file stays 11 bytes long.Example 3 — Create a New File, Then Cut It Short Use the Set overload with CREATE_NEW, write ten digits, truncate to four, and read them back through the same channel.
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;
public class NewByteChannelTruncate {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("demo");
Path file = dir.resolve("digits.txt");
EnumSet<StandardOpenOption> opts = EnumSet.of(StandardOpenOption.CREATE_NEW,
StandardOpenOption.READ, StandardOpenOption.WRITE);
try (SeekableByteChannel ch = Files.newByteChannel(file, opts)) {
ch.write(ByteBuffer.wrap("0123456789".getBytes(StandardCharsets.US_ASCII)));
ch.truncate(4);
System.out.println("Size after truncate: " + ch.size());
ch.position(0);
ByteBuffer buf = ByteBuffer.allocate(10);
ch.read(buf);
buf.flip();
System.out.println("Content: " + StandardCharsets.US_ASCII.decode(buf));
}
try (SeekableByteChannel again = Files.newByteChannel(file, opts)) {
System.out.println("Opened twice?");
} catch (FileAlreadyExistsException e) {
System.out.println("CREATE_NEW again: FileAlreadyExistsException");
}
Files.delete(file);
Files.delete(dir);
}
} Run with java NewByteChannelTruncate. The output is the same on Windows, macOS, and Linux.
Size after truncate: 4
Content: 0123
CREATE_NEW again: FileAlreadyExistsException How It Works Options as a set. EnumSet.of(CREATE_NEW, READ, WRITE) creates a brand-new file that the channel can both write and read.Cut to size. After ten digits, truncate(4) throws away everything after byte 4 and moves the position back to 4.Read from the start. position(0) rewinds, and the 10-byte buffer receives only the four bytes that remain.CREATE_NEW is exclusive. A second open with the same options fails because the file now exists.Frequently Asked Questions What is a SeekableByteChannel? A channel that reads and writes bytes through ByteBuffer objects and has a movable position, so you can access any part of a file.
How do I read a specific part of a file in Java? Open Files.newByteChannel(path), call position(offset), and read into a ByteBuffer of the length you need.
What options does Files.newByteChannel use by default? Just READ. Pass WRITE, CREATE, APPEND, TRUNCATE_EXISTING, or CREATE_NEW to write.
Why must I call flip() on the ByteBuffer? After reading, the buffer position is at the end of the data. flip() sets the limit there and the position back to 0 so the data can be consumed.
Is newByteChannel the same as RandomAccessFile? They serve the same purpose. newByteChannel works with Path, uses ByteBuffer, and supports open options and other file systems.
Next: Files.newDirectoryStream() Iterate the entries of one folder with a for-each loop, optionally filtered by glob or Filter.
newDirectoryStream() tutorial → About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
10 people found this page helpful
Helpful Share Copy link Suggestion