需安装gdal环境,参考Gdal环境配置(Windows系统)
Linux环境可采用docker部署,参考制作Java+Gdal的Docker镜像
本文介绍通过Java+Gdal实现cad文件转为其他空间数据格式,如shapefile、geoJson等。
依赖说明
<!-- 处理CAD文件转换 -->
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-cad</artifactId>
<version>20.10</version>
</dependency>
<!-- gdal sdk -->
<dependency>
<groupId>org.gdal</groupId>
<artifactId>gdal</artifactId>
<version>3.4.1</version>
</dependency>
1、aspose-cad这个jar包可以在这下载:https://download.csdn.net/download/l2931050/87881230
2、gdal这个jar包可以在gdal的安装目录下找到,如:C:\Program Files\GDAL\java
dwg转GeoJson
/**
* 基于gdal实现dwg转GeoJson
* @param dwgPath dwg文件路径
* @return geojson
*/
public static String dwg2GeoJson(String dwgPath) {
gdal.SetConfigOption("DXF_ENCODING", "UTF-8");
//将dwg转成dxf,如果源文件为dxf则跳过该步骤
String dxfPath = CadUtil.dwg2dxf(dwgPath);
//dxf转geojson
DataSource ds = ogr.Open(dxfPath, 0);
Driver driver = ogr.GetDriverByName("GeoJSON");
String geoPath = dxfPath.replace(".dxf", ".geojson");
driver.CopyDataSource(ds, geoPath, null).delete();
ds.delete();
//读取geojson
FileReader fileReader = new FileReader(geoPath, "GBK");
return fileReader.readString();
}
dwg转SHP
/**
* 基于gdal实现dwg转GeoJson
* @param dwgPath dwg文件路径
* @return shp文件路径
*/
public static String dwg2GeoJson(String dwgPath) {
gdal.SetConfigOption("DXF_ENCODING", "UTF-8");
//将dwg转成dxf,如果源文件为dxf则跳过该步骤
String dxfPath = CadUtil.dwg2dxf(dwgPath);
//dxf转geojson
DataSource ds = ogr.Open(dxfPath, 0);
Driver driver = ogr.GetDriverByName("ESRI Shapefile");
String shpPath = dxfPath.replace(".dxf", ".shp");
driver.CopyDataSource(ds, shpPath, null).delete();
ds.delete();
return shpPath;
}
dwg转dxf
import com.aspose.cad.CodePages;
import com.aspose.cad.Image;
import com.aspose.cad.LoadOptions;
import com.aspose.cad.fileformats.cad.CadImage;
import java.io.File;
public class CadUtil {
/**
* dwg文件转dxf文件
* @param dwgPath dwg文件路径
* @return 转换后的dxf文件路径
*/
public static String dwg2dxf(String dwgPath) {
File dwg = new File(dwgPath);
if (dwg.exists()) {
if (!dwg.getName().endsWith(".dwg")) {
System.out.println("文件格式错误");
return "";
}
String outFile = dwg.getAbsolutePath().replace(".dwg", ".dxf");
LoadOptions loadOptions = new LoadOptions();
loadOptions.setSpecifiedEncoding(CodePages.SimpChinese);
CadImage cadImage = (CadImage) Image.load(dwgPath, loadOptions);
cadImage.save(outFile);
cadImage.close();
return outFile;
} else {
System.out.println("dwg文件不存在");
return "";
}
}
}