Hi all,
I try to learn how to create a shapefile with Geotools following
Csv2Shape tutorial [1].
Most of the code (below) is exactly the same as the tutorial code. I
used the csv file as suggested in the tutorial [2].
I just :
1) changed the line
"SimpleFeatureCollection collection = FeatureCollections.newCollection();"
by
"SimpleFeatureCollection collection = new
DefaultFeatureCollection(null,null);"
because FeatureCollections seems deprecated.
2) add a dependency to the pom.xml
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-epsg-hsql</artifactId>
<version>${geotools.version}</version>
</dependency>
*Problem* : the created shapefile does not seem to have geometries :
- when I print the shapefile in QGIS or using the QuickStart
application, it's empty.
- the code above try to print the attributes of the SimpleFeatures
of the shapefile, the result is :
[null, Cape Town, 550]
[null, Victoria, 721]
[null, Lausanne, 560]
[null, Minneapolis, 350]
[null, Ottawa, 200]
[null, Bangkok, 150]
[null, St Paul, 125]
[null, Trento, 140]
+ I don't understand why the last line of the Main
System.out.println("This sentence doesn't print ...");
does not print ...
Hope somebody here can help me again, thank you !
*Code*
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.geotools.styling.Style;
import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.map.FeatureLayer;
import org.geotools.map.Layer;
import org.geotools.map.MapContent;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.swing.JMapFrame;
import org.geotools.swing.data.JFileDataStoreChooser;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import org.geotools.styling.SLD;
/**
* This example reads data for point locations and associated
attributes from a comma separated text
* (CSV) file and exports them as a new shapefile. It illustrates how
to build a feature type.
* <p>
* Note: to keep things simple in the code below the input file should
not have additional spaces or
* tabs between fields.
*/
public class Csv2Shape {
public static void main(String[] args) throws Exception {
File file = JFileDataStoreChooser.showOpenFile("csv", null);
if (file == null) {
return;
}
/*
* We use the DataUtilities class to create a FeatureType that
will describe the data in our
* shapefile.
*
* See also the createFeatureType method below for another,
more flexible approach.
*/
final SimpleFeatureType TYPE = DataUtilities.createType("Location",
"location:Point:srid=4326," + // <- the geometry
attribute: Point type
"name:String," + // <- a String attribute
"number:Integer" // a number attribute
);
/*
* We create a FeatureCollection into which we will put each
Feature created from a record
* in the input csv data file
*/
SimpleFeatureCollection collection = new
DefaultFeatureCollection(null,null);
/*
* GeometryFactory will be used to create the geometry
attribute of each feature (a Point
* object for the location)
*/
GeometryFactory geometryFactory =
JTSFactoryFinder.getGeometryFactory(null);
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
BufferedReader reader = new BufferedReader(new FileReader(file));
try {
/* First line of the data file is the header */
String line = reader.readLine();
System.out.println("Header: " + line);
for (line = reader.readLine(); line != null; line =
reader.readLine()) {
if (line.trim().length() > 0) { // skip blank lines
String tokens[] = line.split("\\,");
double latitude = Double.parseDouble(tokens[0]);
System.out.println("latitude : " + latitude);
double longitude = Double.parseDouble(tokens[1]);
System.out.println("longitude : " + longitude);
String name = tokens[2].trim();
int number = Integer.parseInt(tokens[3].trim());
/* Longitude (= x coord) first ! */
Coordinate coord = new Coordinate(longitude, latitude);
Point point = geometryFactory.createPoint(coord);
featureBuilder.add(point);
featureBuilder.add(name);
featureBuilder.add(number);
SimpleFeature feature = featureBuilder.buildFeature(null);
((DefaultFeatureCollection)
collection).add(feature); }
}
} finally {
reader.close();
}
/*
* Get an output file name and create the new shapefile
*/
File newFile = getNewShapeFile(file);
ShapefileDataStoreFactory dataStoreFactory = new
ShapefileDataStoreFactory();
Map<String, Serializable> params = new HashMap<String, Serializable>();
params.put("url", newFile.toURI().toURL());
params.put("create spatial index", Boolean.TRUE);
ShapefileDataStore newDataStore = (ShapefileDataStore)
dataStoreFactory.createNewDataStore(params);
newDataStore.createSchema(TYPE);
/*
* You can comment out this line if you are using the
createFeatureType method (at end of
* class file) rather than DataUtilities.createType
*/
newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
/*
* Write the features to the shapefile
*/
Transaction transaction = new DefaultTransaction("create");
String typeName = newDataStore.getTypeNames()[0];
SimpleFeatureSource featureSource =
newDataStore.getFeatureSource(typeName);
if (featureSource instanceof SimpleFeatureStore) {
SimpleFeatureStore featureStore = (SimpleFeatureStore)
featureSource;
featureStore.setTransaction(transaction);
try {
featureStore.addFeatures(collection);
transaction.commit();
FeatureIterator featuresIte =
featureStore.getFeatures().features();
featuresIte.next(); //on saute la première ligne déjà
traitée dans l'initialisation
while (featuresIte.hasNext()) {
System.out.println(((SimpleFeature)
featuresIte.next()).getAttributes());
}
} catch (Exception problem) {
problem.printStackTrace();
transaction.rollback();
} finally {
transaction.close();
}
System.exit(0); // success!
} else {
System.out.println(typeName + " does not support
read/write access");
System.exit(1);
}
System.out.println("This sentence doesn't print ...");
}
/**
* Prompt the user for the name and path to use for the output shapefile
*
* @param csvFile
* the input csv file used to create a default shapefile name
*
* @return name and path for the shapefile as a new File object
*/
private static File getNewShapeFile(File csvFile) {
String path = csvFile.getAbsolutePath();
String newPath = path.substring(0, path.length() - 4) + ".shp";
JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
chooser.setDialogTitle("Save shapefile");
chooser.setSelectedFile(new File(newPath));
int returnVal = chooser.showSaveDialog(null);
if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
// the user cancelled the dialog
System.exit(0);
}
File newFile = chooser.getSelectedFile();
if (newFile.equals(csvFile)) {
System.out.println("Error: cannot replace " + csvFile);
System.exit(0);
}
return newFile;
}
}
[1] http://docs.geotools.org/stable/tutorials/feature/csv2shp.html
[2] http://docs.geotools.org/stable/tutorials/_downloads/locations1.csv
------------------------------------------------------------------------------
_______________________________________________
GeoTools-GT2-Users mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/geotools-gt2-users