arcgissamples\geodatabase\—ArcObjects 10.4 Help for Java | ArcGIS for Desktop
Query a shapefile
/* Copyright 2015 ESRI
* All rights reserved under the copyright laws of the United States
* and applicable international laws, treaties, and conventions.
* You may freely redistribute and use this sample code, with or
* without modification, provided you include the original copyright
* notice and use restrictions.
* See the use restrictions at <your ArcGIS install location>/DeveloperKit10.4/userestrictions.txt.
package arcgissamples.geodatabase;


import com.esri.arcgis.datasourcesfile.ShapefileWorkspaceFactory;
import com.esri.arcgis.geodatabase.Feature;
import com.esri.arcgis.geodatabase.FeatureClass;
import com.esri.arcgis.geodatabase.FeatureCursor;
import com.esri.arcgis.geodatabase.Field;
import com.esri.arcgis.geodatabase.Fields;
import com.esri.arcgis.geodatabase.Workspace;
import com.esri.arcgis.geodatabase.esriFieldType;
import com.esri.arcgis.system.AoInitialize;
import com.esri.arcgis.system.EngineInitializer;
import com.esri.arcgis.system.esriLicenseProductCode;
import com.esri.arcgis.system.esriLicenseStatus;

public class QueryShapefile {

  public QueryShapefile(){

   * Main Method - The console application entry point.
   * @param args String[] Command line argument
  public static void main(String[] args) {
    System.out.println("Starting QueryShapefile - An ArcObjects SDK Developer Sample");
      //Initialize engine console application
      //Initialize ArcGIS license
      AoInitialize aoInit = new AoInitialize();
      //Get DEVKITHOME Home
      String devKitHome = System.getenv("AGSDEVKITJAVA");
      //Data access setup
      String inPath = devKitHome + "java" + File.separator + "samples" + File.separator 
                     + "data" + File.separator + "usa";
      String name = "states.shp";
      QueryShapefile thisSampleApp = new QueryShapefile();
      thisSampleApp.printRecordsInShapeFile(inPath, name);
      //Ensure any ESRI libraries are unloaded in the correct order
    }catch(Exception e){
      System.out.println("Error: " + e.getMessage());
      System.out.println("Sample failed.  Exiting...");
   * Checks to see if an ArcGIS Engine Runtime license or an Basic License
   * is available. If so, then the appropriate ArcGIS License is initialized.
   * @param aoInit The AoInitialize object instantiated in the main method.
  private static void initializeArcGISLicenses(AoInitialize aoInit) {
    try {
      if (aoInit.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeEngine) 
          == esriLicenseStatus.esriLicenseAvailable)
      else if (aoInit.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeBasic) 
          == esriLicenseStatus.esriLicenseAvailable)
        System.err.println("Could not initialize an Engine or Basic License. Exiting application.");
    } catch (Exception e) {e.printStackTrace();}
   * Obtain a feature cursor on a shapefile and print the values of each field.
   * @param dataPath A directory path on disk where the source shapefile exists
   * @param featureClassNameString The name of the source shapefile
   * @throws IOException For most anything that goes wrong.
  private void printRecordsInShapeFile(String dataPath, String featureClassNameString) throws IOException {
    try {
      //Get the feature class for the data path and feature class name
      FeatureClass featureClass = getFeatureClass(dataPath, featureClassNameString);
      //Create a feature cursor, and then use it to print out the field headings.
      FeatureCursor featureCursor = new FeatureCursor(, true));
      //Get the number of fields in the feature class
      Fields fields = (Fields) featureCursor.getFields();
      int fieldCount = fields.getFieldCount();

      //Go through each field and print to the console
      for (int index = 0; index < fieldCount; index++) {
        Field field = (Field) fields.getField(index);
        String fieldName = field.getName();
        System.out.print(fieldName + "\t");
      // Use the feature cursor to iterate over all elements in the feature class,
      // printing the values of the fields.  All field types are shown here.  Simple
      // values are printed as Strings.  Complex elements are shown as the type name.
      Feature feature = (Feature) featureCursor.nextFeature();
      while (feature != null) {
        StringBuffer row = new StringBuffer();
        for (int index = 0; index < fieldCount; index++) {
          int fieldType = feature.getFields().getField(index).getType();
          switch (fieldType) {
          case esriFieldType.esriFieldTypeDate:
          case esriFieldType.esriFieldTypeDouble:
          case esriFieldType.esriFieldTypeGlobalID:
          case esriFieldType.esriFieldTypeGUID:
          case esriFieldType.esriFieldTypeInteger:
          case esriFieldType.esriFieldTypeOID:
          case esriFieldType.esriFieldTypeSingle:
          case esriFieldType.esriFieldTypeSmallInteger:
          case esriFieldType.esriFieldTypeString:
            row.append(feature.getValue(index) + "\t");
          case esriFieldType.esriFieldTypeBlob:
            row.append("(blob)" + "\t");
          case esriFieldType.esriFieldTypeGeometry:
            row.append("(geometry)" + "\t");
          case esriFieldType.esriFieldTypeRaster:
            row.append("(raster)" + "\t");
        if (row.length() > 0) {
        feature = (Feature) featureCursor.nextFeature();
    } catch (IOException e) {
      System.out.println("Could not read data.");
      throw e;
   * Get the feature class given the data path and feature class name.
   * @param dataPath The path to the shapefile
   * @param featureClassNameString The feature class name
   * @return FeatureClass object
   * @throws IOException When most any unexpected error occurs
  private FeatureClass getFeatureClass(String path, String name) throws IOException {
    FeatureClass featureClass = null;
    try {
      ShapefileWorkspaceFactory shapefileWorkspaceFactory = new ShapefileWorkspaceFactory();
      Workspace workspace = new Workspace(shapefileWorkspaceFactory.openFromFile(path, 0));
      featureClass = new FeatureClass(workspace.openFeatureClass(name));
    }catch (IOException e) {
      System.out.println("Couldn't access feature class :" + name + " in " + path);
      throw e;
    return featureClass;