Java ProcessBuilder with multiple params with spac

2020-04-12 07:57发布

问题:

I know that there is a lot of solved questions regarding executing processes from java.But I am unable to solve my problem using answers provided. I am trying go create postgresql database backup from java application. I use following code

        //ProcessBuilder probuilder = new ProcessBuilder(new String[]{"cmd","/c","D:/PostgreSQL 8.2/bin/pg_dump.exe","-U","usr","-i","-h","localhost","-p","5432","-F","c","-b","-f","D:/backup test/backups/test_27-1-2013_210.backup", "test"});
        //ProcessBuilder probuilder = new ProcessBuilder(new String[]{"cmd","/c","D:\\PostgreSQL 8.2\\bin\\pg_dump.exe","-U","usr","-i","-h","localhost","-p","5432","-F","c","-b","-f","D:\\backup test\\backups\\test_27-1-2013_210.backup", "test"});
        ProcessBuilder probuilder = new ProcessBuilder(new String[]{"cmd","/c","\"D:\\PostgreSQL 8.2\\bin\\pg_dump.exe\"","-U","usr","-i","-h","localhost","-p","5432","-F","c","-b","-f","\"D:\\backup test\\backups\\test_27-1-2013_210.backup\"", "test"});
        Map<String, String> env = probuilder.environment();
        env.put("PGPASSWORD", "mypass");

        final Process process = probuilder.start();

After executing above code i get following error: D:\PostgreSQL' is not recognized as an internal or external command, operable program or batch file.

Problem occures only when path to backup file contains spaces otherwise backup is created. I have tried to use both slash and backslash in the file path and I quoted file path but i get the same error every time. Command can be executed from command prompt.

What I am doing wrong. Is there some limitations regarding number of parameters with spaces in ProcessBuilder. Thanks

回答1:

Since pg_dump.exe is an exe (not a .bat) you don't need the cmd at all, and it is probably causing more problems than it solves. Just call the exe directly, and remove the extra set of quotes around the file paths:

new String[]{"D:\\PostgreSQL 8.2\\bin\\pg_dump.exe","-U","usr","-i",
  "-h","localhost","-p","5432","-F","c","-b",
  "-f","D:\\backup test\\backups\\test_27-1-2013_210.backup", "test"}