Java SE API

FileChannel.write()

Write bytes from the buffer; result can be less than remaining bytes. See official API for exceptions and overloads; Java 21-compatible example.

Formal Syntax & Structure

java syntaxjava
int write(ByteBuffer src)

Parameters & Attributes

NameTypeDescription
srcByteBufferSource buffer

Return Value

int

Write bytes from the buffer; result can be less than remaining bytes.

Working Example

Example Snippetjava
import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;import java.util.*;public class Main {    static Path item(Path dir, String name) {        if (!name.matches("[a-z]{1,12}\\.(txt|bin)")) {            throw new IllegalArgumentException("Invalid fixture name");        }        return dir.resolve(name);    }    static byte[] bounded(InputStream in, int max) throws IOException {        if (max < 0 || max > 4096) throw new IllegalArgumentException("Invalid limit");        byte[] data = in.readNBytes(max + 1);        if (data.length > max) throw new IOException("Too many bytes");        return data;    }
    public static void main(String[] args) throws Exception {        Path dir = Files.createTempDirectory(Path.of("."), "java-io-");        try {            Path file = item(dir,"data.bin");            try (FileChannel ch = FileChannel.open(file,StandardOpenOption.CREATE_NEW,StandardOpenOption.READ,StandardOpenOption.WRITE)) {                ByteBuffer b = ByteBuffer.allocate(4);                b.putInt(42).flip();                while (b.hasRemaining()) if (ch.write(b) == 0) throw new IOException("No progress");                ch.position(0);                b.clear();                while (b.hasRemaining()) if (ch.read(b) <= 0) throw new EOFException("Incomplete integer");                b.flip();                System.out.println(b.getInt());            }        } finally {            for (String name : List.of("a.txt", "b.txt", "data.bin", "stage.txt", "link.txt")) {                Files.deleteIfExists(dir.resolve(name));            }            Files.delete(dir);        }    }}
Java Reference