How to Write, Convert, and Read WKB Data with JTS in Java
This article explains the WKB binary format, its storage advantages in MySQL and PostgreSQL, and provides step‑by‑step Java code using JTS's GeometryFactory, WKBWriter, and WKBReader to write a Point to WKB, convert it to a hex string, and read it back into a geometry object.
WKB Overview
WKB (Well‑Known Binary) encodes geometric objects as a binary stream using a 1‑byte unsigned integer, a 4‑byte unsigned integer, and 8‑byte double‑precision numbers (IEEE 754). Because it is binary, WKB offers higher transmission and storage efficiency than the text‑based WKT format.
Storing WKB in Databases
Both MySQL and PostgreSQL store geometry column values in WKB format. For example, the MySQL query SELECT hex(st_asbinary(st_geomfromtext('POINT(1 2)'))) returns the hexadecimal representation of a point.
JTS API for WKB
The JTS library provides classes for WKB operations. The following diagram shows the relevant API (image omitted for brevity).
Writing WKB and Converting to Hex
GeometryFactory geometryFactory = new GeometryFactory();
Point point1 = geometryFactory.createPoint(new Coordinate(112.11, 2225.21));
WKBWriter wkbWriter = new WKBWriter();
byte[] write = wkbWriter.write(point1);
String hex = WKBWriter.toHex(write);
System.out.println(hex); // 0000000001405C070A3D70A3D740A1626B851EB852Reading WKB Back to Geometry
WKBReader wkbReader = new WKBReader();
Geometry geometry = null;
try {
geometry = wkbReader.read(write);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(geometry.toText()); // POINT (112.11 2225.21)Complete Example
// Write WKB
GeometryFactory geometryFactory = new GeometryFactory();
Point point1 = geometryFactory.createPoint(new Coordinate(112.11, 2225.21));
WKBWriter wkbWriter = new WKBWriter();
byte[] write = wkbWriter.write(point1);
String hex = WKBWriter.toHex(write);
System.out.println(hex); // 0000000001405C070A3D70A3D740A1626B851EB852
// Read WKB
WKBReader wkbReader = new WKBReader();
Geometry geometry = null;
try {
geometry = wkbReader.read(write);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(geometry.toText()); // POINT (112.11 2225.21)Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
The Dominant Programmer
Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
