Search code examples
javageotools

Rename Shape File which saves as TableName using Geotools - JAVA


I am trying to save a shapefile which works fine as followed by this question link here:

Add new column attribute to the shapefile and save it to database using Geotools Java

The problem I face is with the fileName of the shapefile, which contains a blank space and it turns out to save as %20 equivalent to space n db.

For eg: New File abc.shp ==> New%20File%20abc (TableName)

I know we could rename the filePath, but in my case i want to rename the file chosen, as opposed to renaming a file on the filesystem.

EDIT

Using Geotools I am using the following code to store the tableName:

  File FilePath = new File("/users/New File abc.shp");
 FileDataStore ds = FileDataStoreFinder.getDataStore(new File(FilePath.toString()));
    SimpleFeatureType schema = ds.getSchema();
    // create new schema
    SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
    builder.setName(schema.getName());
    builder.setSuperType((SimpleFeatureType) schema.getSuper());
    builder.addAll(schema.getAttributeDescriptors());

    // build new schema
    SimpleFeatureType nSchema = builder.buildFeatureType();
    System.out.println("Shapefile table info : " + nSchema);

Is there any way I could do it using Java or is there any solution using Geotools. The DB I am using is PostGIS.


Solution

  • The answer seems pretty simple, because I was only focusing on changing the filePath. But a simple solution as per Ian's comment gave me the idea. I just had to rename the schema name after loading the file.

    The code snippet is as follows:

     File FilePath = new File("/users/New File abc.shp");
     FileDataStore ds = FileDataStoreFinder.getDataStore(new File(FilePath.toString()));
        SimpleFeatureType schema = ds.getSchema();
        // create new schema
        SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
        builder.setName(schema.getName().toString().replaceAll("%20", "_").replaceAll(" ", "_"));
        builder.setSuperType((SimpleFeatureType) schema.getSuper());
        builder.addAll(schema.getAttributeDescriptors());
    
        // build new schema
        SimpleFeatureType nSchema = builder.buildFeatureType();
        System.out.println("Shapefile table info : " + nSchema);
    

    Just a note, we could also change the fileName using renameTo in java, but that causes to change the other file in shapefile which is not a good idea if ur scaling an application like this.