简体   繁体   中英

How to perform a shell redirection (command > output.txt) using ProcessBuilder?

I wanted to backup a MySQL database using ProcessBuilder and the > character is not being interpreted as I expected. This is my code:

java.util.List<String> cmd = new java.util.ArrayList<>();
cmd.add("mysqldump");
cmd.add("-u");
cmd.add("root");
cmd.add("-p"+password);
cmd.add("DBx");
cmd.add(">");
cmd.add("DBbk.sql");

ProcessBuilder pb = new ProcessBuilder(cmd);
pb.directory(new File("."));
Process p = pb.start();
p.waitFor();

BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while((line = err.readLine()) != null) {
    System.out.println(line);
}

The output is:

Warning: Using a password on the command line interface can be insecure.
mysqldump: Couldn't find table: ">"

The process builder is executing the program directly, not executing it through a shell/command prompt. Therefore, you don't get any nice features of the shell like the > character for redirection. Sorry.

Give this a try (just displaying the significant portion of the solution):

new ProcessBuilder("cmd", "/C", "your_command > DBbk.sql").start() 

This way you're explicitly calling cmd . In Linux you could call bash or whatever shell you use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM