Shapefile格式文件解析和显示
Java实现GIS SHP文件格式的解析和显示,JDK19下编译,awt图形系统显示。
SHP文件对应的属性存储在DBF格式数据库中,解析见:DBASE DBF数据库文件解析_数据库文件在线解析-CSDN博客
解析SHP文件代码:
public static Shapefile parse(String file) throws IOException {
byte _bytes[] = Files.readAllBytes(Paths.get(file)); // 读取文件内容
BinaryBufferArray bis = new BinaryBufferArray(_bytes, ByteOrder.BIG_ENDIAN); // 设置大端模式
ShapefileImpl shp = new ShapefileImpl();
shp.magic = bis.ReadUInt32(); // 读取标志
bis.ReadInt32();
bis.ReadInt32();
bis.ReadInt32();
bis.ReadInt32();
bis.ReadInt32();
shp.length = bis.ReadUInt32(); // 读取长度
bis.SetByteOrder(ByteOrder.LITTLE_ENDIAN); // 切换小端模式
shp.version = bis.ReadUInt32(); // 读取版本号
shp.type = bis.ReadInt32();
shp.mbr = bis.ReadDouble(4);
shp.z = bis.ReadDouble(2);
shp.m = bis.ReadDouble(2);
while (bis.available() > 0) {
bis.SetByteOrder(ByteOrder.BIG_ENDIAN); // 切换大端模式
int gno = bis.ReadInt32();
long glen = bis.ReadUInt32(); // 按16-bit word为1个内容长度,这样内容长度是16bit为单位计算的
bis.SetByteOrder(ByteOrder.LITTLE_ENDIAN); // 切换小端模式
long gtype = bis.ReadUInt32(); // 图形类型
if (gtype == 5) { // Polygon // 测试文件仅有多边形,程序只实现了多边形
double[] box = bis.ReadDouble(4);
int NumParts = bis.ReadInt32();
int NumPoints = bis.ReadInt32();
int[] Parts = bis.ReadInt32(NumParts);
ArrayList<SHPPolygon> ps = new ArrayList<>(); // 多边形存储列表
for (int i=0; i<NumParts; i++) {
int n = (i==NumParts-1 ? NumPoints- Parts[i] : Parts[i+1] - Parts[i] );
SHPPoint[] _points = new SHPPoint[n];
for (int j=0;j<n;j++)
_points[j] = new SHPPoint(bis.ReadDouble(), bis.ReadDouble());
SHPPolygon p = new SHPPolygon(_points);
ps.add(p);
}
SHPPolygonArray p = new SHPPolygonArray(gno, box, ps);
shp.geos.add(p);
}
else
throw new java.lang.UnsupportedOperationException("" + gtype);
}
return shp;
}
使用AWT显示世界地图绘制结果,未采用双缓冲模式有闪烁,当鼠标移动时在状态栏显示国家地名属性,从DBF文件解析获得