arcgissamples\geodatabase\QueryShapefile.java—ArcObjects 10.4 Help for Java | ArcGIS for Desktop
Query a shapefile
arcgissamples\geodatabase\QueryShapefile.java
/* 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 java.io.File;
import java.io.IOException;

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");
    
    try{
      //Initialize engine console application
      EngineInitializer.initializeEngine();
      
      //Initialize ArcGIS license
      AoInitialize aoInit = new AoInitialize();
      initializeArcGISLicenses(aoInit);
      
      //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);
      
      System.out.println("Done.");      
      
      //Ensure any ESRI libraries are unloaded in the correct order
      aoInit.shutdown();
    }catch(Exception e){
      System.out.println("Error: " + e.getMessage());
      System.out.println("Sample failed.  Exiting...");
      e.printStackTrace();
      System.exit(-1);
    }
  }
  
  /**
   * 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)
        aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeEngine);
      else if (aoInit.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeBasic) 
          == esriLicenseStatus.esriLicenseAvailable)
        aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeBasic);
      else{
        System.err.println("Could not initialize an Engine or Basic License. Exiting application.");
        System.exit(-1);
      }
    } 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(featureClass.search(null, 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");
      }
      
      System.out.println();
      
      // 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");
            break;
            
          case esriFieldType.esriFieldTypeBlob:
            row.append("(blob)" + "\t");
            break;
            
          case esriFieldType.esriFieldTypeGeometry:
            row.append("(geometry)" + "\t");
            break;
            
          case esriFieldType.esriFieldTypeRaster:
            row.append("(raster)" + "\t");
            break;
          }
        }
        
        if (row.length() > 0) {
          System.out.println(row);
        }
        
        feature = (Feature) featureCursor.nextFeature();
      }
    } catch (IOException e) {
      System.out.println("Could not read data.");
      System.out.println(e.getMessage());
      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;
  }
}