Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

DataOutputStream — writing binary data

DataOutputStream writes primitive values and strings to a binary stream in a defined format. Learn the byte widths, byte order, and limitations of writeUTF.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

new DataOutputStream(OutputStream out)
void writeByte(int v) throws IOException
void writeInt(int v) throws IOException
void writeDouble(double v) throws IOException
void writeUTF(String str) throws IOException

DataOutputStream from java.io wraps an OutputStream and writes binary data rather than textual representations. Reading with DataInputStream must match the order and types of the written values.

DataOutputStream.writeByte(int) writes only the lowest 8 bits: 257 produces byte 0x01, without range validation. DataOutputStream.writeInt(int) writes 4 bytes in big-endian order, most significant first. DataOutputStream.writeDouble(double) writes 8 bytes in that same order after conversion through Double.doubleToLongBits.

DataOutputStream.writeUTF(String) writes a two-byte payload length in bytes, followed by modified UTF-8. This is not ordinary UTF-8: NUL takes 2 bytes, and supplementary characters are encoded as surrogate pairs. The limit is 65535 encoded payload bytes, not characters; exceeding it causes UTFDataFormatException.

Write methods can throw IOException. Sharing the stream between threads requires synchronization. The example displays the expected 17 bytes in hexadecimal. The documentation scope is Java SE 21; neither the repository runtime nor the production runtime has been attested.

Examples

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.HexFormat;

public class Main {
    public static void main(String[] args) throws IOException {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (DataOutputStream out = new DataOutputStream(bytes)) {
            out.writeByte(257);
            out.writeInt(42);
            out.writeDouble(1.5);
            out.writeUTF("OK");
        }
        System.out.println(HexFormat.of().formatHex(bytes.toByteArray()));
    }
}

Result

010000002a3ff800000000000000024f4b

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources