Java Files newByteChannel() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Java 7+

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:

Java
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
CallWhat 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
Java
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

ParameterDescription
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 ValueDescription
SeekableByteChannelAn open channel at position 0 (or at the end with APPEND).

Compare with Similar Methods

Streams vs channels:

MethodHow it differs
newInputStream()Forward-only reading.
newOutputStream()Forward-only writing.
size()File size without opening a channel.

Java Examples

Example 1 — Jump to the End of a File

Set the position to five bytes before the end and read just those bytes.

Java
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);
    }
}

How It Works

  1. Read-only by default. With no options, the channel opens the existing file for reading.
  2. Seek, then read. The text has 15 bytes, so position(10) skips Hello, chan and lands on the second n.
  3. 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.

Java
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);
    }
}

How It Works

  1. WRITE alone keeps the data. Without TRUNCATE_EXISTING the file is not emptied, so only the bytes you write change.
  2. Byte 6 is the W. "Hello " is six bytes (0 to 5), so writing at position 6 replaces World.
  3. 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.

Java
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);
    }
}

How It Works

  1. Options as a set. EnumSet.of(CREATE_NEW, READ, WRITE) creates a brand-new file that the channel can both write and read.
  2. Cut to size. After ten digits, truncate(4) throws away everything after byte 4 and moves the position back to 4.
  3. Read from the start. position(0) rewinds, and the 10-byte buffer receives only the four bytes that remain.
  4. CREATE_NEW is exclusive. A second open with the same options fails because the file now exists.

Frequently Asked Questions

A channel that reads and writes bytes through ByteBuffer objects and has a movable position, so you can access any part of a file.
Open Files.newByteChannel(path), call position(offset), and read into a ByteBuffer of the length you need.
Just READ. Pass WRITE, CREATE, APPEND, TRUNCATE_EXISTING, or CREATE_NEW to write.
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.
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

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

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