Java ProcessBuilder with multiple params with spaces

让人想犯罪 __ 提交于 2019-12-02 01:27:16

问题


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"}


来源:https://stackoverflow.com/questions/15111517/java-processbuilder-with-multiple-params-with-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!