Datta
Datta

Reputation: 87

How to use processbuilder to run piped processes in windows

processbuilder does not allow redirecting inputstream/output streams. How can I create piped processes in java? I tried to use this command but it doesn't work.

process = Runtime.getRuntime().exec("cmd","sort < randomwords.txt | sort /R >reversesortes.txt");

EDIT: Still this is not working.

ArrayList<String> cmd = new ArrayList<>(); 
String s = "/R"; 
cmd.add("cmd"); 
cmd.add("sort"); 
cmd.add("<"); 
cmd.add("randomwords.txt"); 
cmd.add("|"); 
cmd.add("sort"); 
cmd.add("/R"); 
cmd.add( ">"); 
cmd.add("reversesortes.txt"); 
ProcessBuilder builder = new ProcessBuilder(cmd); 
builder.redirectError(new File("error.txt")); 
Process process = builder.start(); 
System.out.println("im here" ); 
int i = process.waitFor(); 
System.out.println("i"+ i );

Upvotes: 0

Views: 1558

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148880

As the name of the shell is cmd, I assume that your OS is Windows. cmd.exe requires a /c to introduce a command passed as parameter. In an interactive shell, this command:

C:\Users\sj>cmd echo foo
Microsoft Windows [version 6.0.6002]
Copyright (c) 2006 Microsoft Corporation. Tous droits réservés.

C:\Users\sj>

only opens a new interactive shell waiting for commands on its standard input whereas

C:\Users\sj>cmd /c echo foo
foo

C:\Users\sj>

correctly executes the command passed as parameter.

So you should write:

ArrayList<String> cmd = new ArrayList<>(); 
cmd.add("cmd"); 
cmd.add("/C"); 
cmd.add("sort < randomwords.txt | sort /R >reversesortes.txt"); 
ProcessBuilder builder = new ProcessBuilder(cmd); 
builder.redirectError(new File("error.txt")); 
Process process = builder.start(); 

Upvotes: 2

Related Questions