GeoTools(http://www.geotools.org)는 자바 기반의 GIS 시스템을 구축할 수 있는 다양한 기능을 갖춘 오픈소스입니다. 제가 처음 GeoTools에 관심을 가졌던 이유는 SHP 파일을 읽기 위한 자바 라이브러리가 필요해서 였는데요. 이 기능을 파악하기 위해 테스트로 작성했던 코드를 공유해 봅니다.
먼저 SHP 파일에서 좌표를 읽어 들이는 코드입니다.
import java.io.IOException;
import java.net.MalformedURLException;
import org.geotools.data.shapefile.shp.ShapefileException;
import org.geotools.data.shapefile.shp.ShapefileReader;
import org.geotools.data.shapefile.shp.ShapefileReader.Record;
import org.geotools.data.shapefile.ShpFiles;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
public class ShapefileReaderTestMainEntry {
public static void main(String[] args) {
ShapefileReader r = null;
try {
ShpFiles shpFile = new ShpFiles("G:\\__Data__\\dong.shp");
GeometryFactory geometryFactory = new GeometryFactory();
r = new ShapefileReader(shpFile, true, false, geometryFactory);
while (r.hasNext()) {
Record record = r.nextRecord();
Geometry shape = (Geometry)record.shape();
Point centroid = shape.getCentroid();
System.out.println(
"("
+ centroid.getX()
+ ", "
+ centroid.getY()
+ ")"
);
}
r.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (ShapefileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
};
}
}
다음으로는 DBF 파일에서 값을 읽어 들이는 코드입니다.
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import org.geotools.data.shapefile.ShpFiles;
import org.geotools.data.shapefile.dbf.DbaseFileHeader;
import org.geotools.data.shapefile.dbf.DbaseFileReader;
public class DbaseFileReaderTestMainEntry {
public static void main(String[] args) {
DbaseFileReader r = null;
try {
ShpFiles shpFile = new ShpFiles("G:\\__Data__\\dong.shp");
r = new DbaseFileReader(shpFile, false, Charset.defaultCharset());
DbaseFileHeader header = r.getHeader();
int numFields = header.getNumFields();
for(int iField=0; iField < numFields; ++iField) {
String fieldName = header.getFieldName(iField);
System.out.println(fieldName);
}
while (r.hasNext()) {
Object[] values = r.readEntry();
for(int iField=0; iField < numFields; ++iField) {
System.out.println(values[iField].toString());
}
System.out.println("---------------");
}
r.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}