Skip to content

Instantly share code, notes, and snippets.

@termat
Last active November 8, 2015 09:15
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save termat/fb1fbcac9ef6ff9db2f1 to your computer and use it in GitHub Desktop.
ShapeファイルをGeoJSONに変換する。 ref: http://qiita.com/t-mat/items/562d71e62102cc906152
package modules;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.Charset;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geojson.feature.FeatureJSON;
public class Shape2GeoJSON {
public static String getJSON(File f,String encoding)throws Exception{
f.setReadOnly();
ShapefileDataStore store = new ShapefileDataStore(f.toURI().toURL());
Charset cs=Charset.forName(encoding);
store.setCharset(cs);
SimpleFeatureSource source = store.getFeatureSource();
SimpleFeatureCollection featureCollection = source.getFeatures();
String geoJson=null;
FeatureJSON fj = new FeatureJSON();
StringWriter writer = new StringWriter();
fj.writeFeatureCollection(featureCollection, writer);
geoJson = writer.toString();
return geoJson;
}
public static File getGeoJSON(String json,String path,String encoding) throws Exception{
File out=new File(path);
PrintWriter pw=null;
try{
FileOutputStream fos = new FileOutputStream(out);
OutputStreamWriter osw = new OutputStreamWriter(fos,encoding);
pw = new PrintWriter(osw);
pw.write(json);
pw.close();
pw=null;
return out;
}catch(IOException e){
e.printStackTrace();
}finally{
if(pw!=null){
pw.close();
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment