Data Streams Primitive Roundtrip
Write ints, shorts, strings, and longs at fixed widths with DataOutputStream, then read them back in the same order with DataInputStream.
Code
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
public class HeaderCodec {
public static void main(String[] args) throws IOException {
ByteArrayOutputStream raw = new ByteArrayOutputStream();
// DataOutputStream 按大端固定宽度写出各 primitive 原始类型
try (var out = new DataOutputStream(raw)) {
out.writeInt(0x57_41_56_45); // 4 字节魔数
out.writeShort(2); // 2 字节版本号
out.writeUTF("sensor-a"); // modified UTF-8,前置 2 字节长度
out.writeLong(1710000000123L); // 8 字节时间戳
}
byte[] frame = raw.toByteArray();
System.out.println("frame bytes: " + frame.length);
// DataInputStream 严格按写出顺序读回 roundtrip,顺序错位即乱值
try (var in = new DataInputStream(new ByteArrayInputStream(frame))) {
int magic = in.readInt();
short version = in.readShort();
String name = in.readUTF();
long capturedAt = in.readLong();
System.out.println("magic=" + magic + " version=" + version
+ " name=" + name + " at=" + capturedAt);
}
}
}What the code does
The working surface is the class HeaderCodec — everything else is wiring.
Resources live in the try header, so closing is compiler-generated and exception-safe.
Applying it
Running the file prints labeled results such as frame bytes:, magic= — each operation’s effect is visible in the output.
Statements that matter
out.writeUTF("sensor-a"); // modified UTF-8,前置 2 字节长度
out.writeLong(1710000000123L); // 8 字节时间戳
}
ByteArrayOutputStream raw = new ByteArrayOutputStream();
byte[] frame = raw.toByteArray();
Interactive Tools for This Topic
FAQ
- What does Data Streams Primitive Roundtrip print when run?
- Execute the whole file; each printed line is prefixed with a label like `frame bytes:`, `magic=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.