javageotools

Read ESRI Shapefile in Java (.dbf) using geoTools


im trying to get the attribute table from esri shapefiles in java but i only managed to get the header table using Geotools library ? Here is my source code :

        File dbfFile = new File("C:/Users/ilyasse2.0/Desktop/shapefiles/marocShp/mar_admbndp_admALL_unhcr_itos_20201203.dbf");
        FileInputStream fis = new FileInputStream(dbfFile);
        DbaseFileReader dbfReader = new DbaseFileReader(fis.getChannel(), false, Charset.forName("ISO-8859-1"));
        DbaseFileHeader dbfHeader = dbfReader.getHeader();
        System.out.println(dbfHeader.getRecordLength());
        List<String> names = new Vector<String>();
        int n = dbfHeader.getNumFields();
        for (int i = 0; i < n; i++) names.add(dbfHeader.getFieldName(i));
        System.out.println(names);

Solution

  • You need to use a ShapefileDataStore to read a Shapefile, you can then iterate through the features and extract the attributes. Note: the file should end in .shp, GeoTools will find the other necessary files.

    List attributes = new ArrayList<>();
    FileDataStore store = FileDataStoreFinder.getDataStore(file);
    SimpleFeatureSource source = store.getFeatureSource();        
    FeatureType schema = source.getSchema();
    
    try(SimpleFeatureCollection features = source.getFeatures();SimpleFeatureIterator iterator =  featureCollection.features()) {
        while (iterator.hasNext()) {
            // copy the contents of each feature and transform the geometry
            SimpleFeature feature = iterator.next();
            attributes.add(feature.getAttributes());
         }
    
     }