hacene abdessamed hacene abdessamed - 1 year ago 178
Java Question

Create backup of postgresql via ProcessBuilder

I want to create a backup of my database using pg_dump in java. The creation of backup works fine, but it doesn't start before the program exits.

Is there any way to start the backup instantly?

public static void backupDb() throws IOException, InterruptedException {
String path = "C:\\HACENE\\test.backup";
Runtime r = Runtime.getRuntime();
//PostgreSQL variables
String host = "localhost";
String user = "postgres";
String dbase = "gtr_bd";
String password = "postgres";
Process p;
ProcessBuilder pb;

r = Runtime.getRuntime();
pb = new ProcessBuilder("C:\\Program Files\\PostgreSQL\\9.3\\bin\\pg_dump", "-v", "-h", host, "-f", path, "-U", user, dbase);
pb.environment().put("PGPASSWORD", password);
p = pb.start();
System.out.println("end of backup");

Answer Source

If you excute this command in cmd this work fine:

"C:\Program Files\PostgreSQL\9.3\bin\pg_dump.exe" -U postgres -h localhost -p 5432 database_name > "C:\Test\test.buckup"

So what i do, that i put this lines in a .bat file like this:

@echo off
cd "C:\Program Files\PostgreSQL\9.3\bin\" 
pg_dump.exe -U postgres -h localhost -p 5432 bd_suivi > "C:\Test\test.buckup"

And excuted this file.bat with java, like this:

public static void main(String[] args) {
    try {
        ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "start C:\\Users\\laidani.youcef\\Desktop\\commandBAT.bat");
        Process p = builder.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while (true) {
            line = r.readLine();
            if (line == null) {
        System.out.println("I finished the creation of the buckup!");
    } catch (Exception e) {
        System.out.println("Exception = " + e);

good luck,

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download