arcgissamples\geodatabase\UpdateFeatures.java—ArcObjects 10.4 Help for Java | ArcGIS for Desktop
Update features using an update cursor
arcgissamples\geodatabase\UpdateFeatures.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.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

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.Workspace;
import com.esri.arcgis.geodatabase.esriFieldType;
import com.esri.arcgis.geometry.Point;
import com.esri.arcgis.geometry.esriGeometryType;
import com.esri.arcgis.system.AoInitialize;
import com.esri.arcgis.system.Cleaner;
import com.esri.arcgis.system.EngineInitializer;
import com.esri.arcgis.system.esriLicenseProductCode;
import com.esri.arcgis.system.esriLicenseStatus;

public class UpdateFeatures {

  public UpdateFeatures(){
    
  }
  
  /**
   * Main Method - The console application entry point.
   * 
   * @param args String[] Command line argument
   */
  public static void main(String[] args) {
    System.out.println("Starting UpdateFeatures - 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 inName = "wind.shp";
      
      //Data output setup
      File inFile = new File(inPath, inName);
      
      String prefix = inName + ".copy";
      String suffix = "";
      
      File inPathFile = new File(inPath);
      File backupFile = null;
      backupFile = File.createTempFile(prefix, suffix, inPathFile);

      //Make a backup copy, since we'll be changing the source file
      FileChannel in = new FileInputStream(inFile).getChannel();
      FileChannel out = new FileOutputStream(backupFile).getChannel();
      long numbytes = in.size();
      in.transferTo(0, numbytes, out);
      in.close();
      out.close();

      System.out.println("The input shape file " + inName + " will be modfied! \nBackup created: " + backupFile.getAbsolutePath());
      
      UpdateFeatures thisSampleApp = new UpdateFeatures();
      thisSampleApp.addXYValues(inPath, inName);
      
      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();}
  }

  /**
   * Insert x,y fields into a shapefile with x,y values.
   *
   * @param path the shapefile path
   * @param name the shapefile name
   * @throws IOException when cannot access or modify the shapefile
   */
  private void addXYValues(String path, String name) throws IOException {
    try {
      String xFieldName = "textX";
      String yFieldName = "textY";

      // Get the feature class for the point shapefile.
      FeatureClass featureClass = getPointShapefileFeatureClass(path, name);

      // Get the indices to the textX and textY fields in the shapefile, if they exist,
      // and if they don't, create those fields in the shapefile.
      int xFieldIndex = -1;
      if ((xFieldIndex = featureClass.findField(xFieldName)) == -1) {
        Field field = new Field();
        field.setName(xFieldName);
        field.setType(esriFieldType.esriFieldTypeDouble);
        featureClass.addField(field);
        xFieldIndex = featureClass.findField(xFieldName);
      }
      
      int yFieldIndex = -1;
      if ((yFieldIndex = featureClass.findField(yFieldName)) == -1) {
        Field field = new Field();
        field.setName(yFieldName);
        field.setType(esriFieldType.esriFieldTypeDouble);
        featureClass.addField(field);
        yFieldIndex = featureClass.findField(yFieldName);
      }

      // Get a feature cursor for this feature class that has no filter and
      // will not recycle.
      FeatureCursor featureCursor = new FeatureCursor(featureClass.IFeatureClass_update(null, false));

      // For each (point) feature, get its point from its shape, and use
      // its coordinates to set values in the x and y fields for
      // that feature.
      System.out.print("Updating feature X,Y fields values for each feature ...");
      Feature feature = (Feature) featureCursor.nextFeature();
      while (feature != null) {
        Point point = (Point) feature.getShape();
        
        feature.setValue(xFieldIndex, new Double(point.getX()));
        feature.setValue(yFieldIndex, new Double(point.getY()));
        
        featureCursor.updateFeature(feature);
        
        feature = (Feature) featureCursor.nextFeature();
      }

      featureCursor.flush();
      Cleaner.release(featureCursor);
    }catch (IOException e) {
      System.out.println("Could not update shapefile.");
      System.out.println(e.getMessage());
      e.printStackTrace();
      throw e;
    }
  }
  
  /**
   * Get a point feature shapefile's feature class
   *
   * @param shapefilePath path to the shapefile which gets modified.
   * @param shapefileName name of the shapefile which gets modified.
   * @return IFeatureClass object representing the feature class for the shapefile.
   * @throws IOException if couldn't get the feature class from the shapefile, or wasn't a point feature shapfeile
   */
  private FeatureClass getPointShapefileFeatureClass(String shapefilePath, String shapefileName) throws IOException {
    FeatureClass featureClass = null;
    
    try {
      ShapefileWorkspaceFactory shapefileWorkspaceFactory = new ShapefileWorkspaceFactory();
      
      Workspace shapefileWorkspace = new Workspace(shapefileWorkspaceFactory.openFromFile(shapefilePath, 0));
      
      featureClass = new FeatureClass(shapefileWorkspace.openFeatureClass(shapefileName));

      // Insure this shapefile holds point features.
      if (featureClass.getShapeType() != esriGeometryType.esriGeometryPoint) {
        throw new IOException("This sample requires a point shapefile.");
      }
    }catch (IOException e) {
      System.out.println("Could not open or use shapefile " + shapefileName + " at location " + shapefilePath);
      throw e;
    }
    
    return featureClass;
  }
}