How to convert shp to csv

المشرف العام

Administrator
طاقم الإدارة
I am trying to convert my shape files to csv through a batch processing in Java using Geotools. The problem is I have more than 500 shape files (point features). The code is working fine for a small number of shp files. But when I am iterating the process over a large dataset (number of files), some of the files are not written and of 0 KB. I have no clue why this is happening. Any help would be highly appreciated. I want all the files to be converted from shp to csv. Here is my java code-

// shp2csv conversionimport java.io.BufferedWriter;import java.io.File;import java.io.FileWriter;import java.io.IOException;import org.geotools.data.FileDataStore;import org.geotools.data.FileDataStoreFinder;import org.geotools.data.shapefile.ShapefileDataStore;import org.geotools.data.simple.SimpleFeatureCollection;import org.geotools.data.simple.SimpleFeatureIterator;import org.geotools.data.simple.SimpleFeatureSource;import org.opengis.feature.simple.SimpleFeature;public class GeoOpen{private static SimpleFeatureIterator simpleFeatureIterator;static FileDataStore store ;static String ID="";public static boolean openShapeFile(File srcfname) throws Exception{ String filename=srcfname.getAbsolutePath(); File dataFile = new File(filename); dataFile.setReadOnly(); store = FileDataStoreFinder.getDataStore(dataFile); // ShapefileDataStore store = new ShapefileDataStore(dataFile.toURL()); SimpleFeatureSource source = store.getFeatureSource(); SimpleFeatureCollection featureCollection = source.getFeatures(); simpleFeatureIterator = featureCollection.features(); return true;}public static boolean iterate(File srcfname, String dest_path){ File dest_file=srcfname; String dest_filename=GeoOpen.getFileNameWithoutExtension(dest_file)+".csv"; try{ BufferedWriter bw=new BufferedWriter (new FileWriter(dest_path+dest_filename)); bw.write("ID"+","+ "date"+","+"tstamp"+","+"X_prj"+","+"Y_prj"+","+"NEAR_FID"+","+"NEAR_DIST"); while(simpleFeatureIterator.hasNext()) { SimpleFeature f = simpleFeatureIterator.next(); // System.out.println(""+f.getID()+" ,"+f.getAttribute(1)+", "+f.getAttribute(2)); //ID, field 1: lat, field 2: long //writing in a CSV file bw.write("\n"); int index = f.getID().lastIndexOf('.'); ID=f.getID().substring(index+1); //get only the ID //by default ID comes with filename.ID format when getID() method called bw.write(Integer.parseInt(ID)+" ,"+f.getAttribute(1).toString()+", "+f.getAttribute(2)+","+f.getAttribute(3)+","+f.getAttribute(4)+","+f.getAttribute(5)+","+f.getAttribute(6)); } } catch (IOException e) { e.printStackTrace(); } catch(Exception ex){ ex.printStackTrace(); } finally{ simpleFeatureIterator.close(); store.dispose(); } return true;}public static String getFileNameWithoutExtension(File f){ String s=""; int index = f.getName().lastIndexOf('.'); //System.out.println (index); if (index>0&& index
 
أعلى