I have to import a shapefile to PostgreSQL via a Java application. There are few codes that I've found and the code I've tried:

package shptodb;

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;

public class processbuilder {
    public static void main( String[] args) {
         ProcessBuilder pb= new ProcessBuilder();
         pb.command("cmd.exe", "shp2pgsql  -s 4326 C:\\Geodata\\Provinces.shp provinces | psql -U postgres -h localhost -p 5433 -d DB"
        try {

                Process process = pb.start();

                StringBuilder output = new StringBuilder();

                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(process.getInputStream()));

                String line;
                while ((line = reader.readLine()) != null) {
                    output.append(line + "\n");

                int exitVal = process.waitFor();
                if (exitVal == 0) {
                } else {

            } catch (IOException e) {
            } catch (InterruptedException e) {

I don't get any errors, so I don't know what's wrong with my code.

  • 1
    This isn't really "using Java", since all you're doing is invoking an executable. Have you tried using the shp2pgsql utility directly? Using the administrative login to load user data is an anti-pattern that can result in destruction of the database.
    – Vince
    Mar 14 at 12:04
  • I need to import the shapefile into database via code , the importation of the shapefile via the CMD version of shp2pgsql works fine . So I found that we can run cmd commands throught Java process Builder and that what I was trying to do. is there any way to do the importation using Java ?
    – Fatima22
    Mar 14 at 12:20
  • Invoking interprocess communication in a subprocess is particularly fraught (and not particularly GIS-centric -- Stack Overflow is probably a better place to research this). There are of course dozens of potential ways to do this with GIS tools, but you'd need to choose one and try it before the Question could be sufficiently focused.
    – Vince
    Mar 14 at 12:37


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.