Reputation: 137
I am trying to use ProcessBuilder in Java and I am not quite getting how to split up my arguments for it. For example, this command + arguments find . -name 'rc*'
. Here below are few different argument splits and none of them are giving me the correct result. Any idea what I am doing wrong in the argument splitting?
//This is obvious error since I mixed arugments with the command
processBuilder.command("find . -name 'rc*'").directory(new File("/etc"))
//Gives me exit code 1 and no results
processBuilder.command("find", ". -name 'rc*'").directory(new File("/etc"))
//Gives me also exit code 1 and no results
processBuilder.command("find", ".", "-name", "'rc*'").directory(new File("/etc"))
//Gives me also exit code 1 and no results
processBuilder.command("find", ". -name", "'rc*'").directory(new File("/etc"))
//Gives me also exit code 1 and no results
processBuilder.command("find", ".", "-name 'rc*'").directory(new File("/etc"))
EDIT
When I tried to add .inheritIO(), and split all arguments, to this it worked partially that is I got printouts for files that have Permission denied.
processBuilder.command("find", ". -name 'rc*'").directory(new File("/etc")).inheritIO();
but as before it did not list my other "rc" files.
Listing all rc files in /etc directory:
//Here should be at least dozen files that print out when I use the command in terminal
Exit code: 1
find 'someFileName': Permission denied
find 'someFileName': Permission denied
find 'someFileName': Permission denied
My process and printout part
Process b;
b.processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(b.getInputStream()));
String line = "";
while((line = reader.readLine()) != null){
System.out.println(line);
}
SECOND EDIT
The thing is that if I change the ProcessBuilder command to a similar command (I guess) then it prints out the resulting files with no prob with the same code - i.e. I changed the command to ls -a
like
processBuilder.command("ls","-a").directory(new File("/etc")).inheritIO();
//and then activate the process and print it just as before and all good ```
Upvotes: 1
Views: 905
Reputation: 15116
The launch is from Java so there is no need to escape the find parameter rc*
with single quotes. A shell such as bash would expand rc*
to actual files prefixed with "rc" in the current directory (and use wrong search value), but Java will not do that. Also every parameter must be in its own string:
processBuilder.command("find", ".", "-name", "rc*").directory(new File("/etc"));
or
processBuilder.command("find", "/etc", "-name", "rc*");
If find is reporting a lot of errors you may get problem that the process freezes because you don't read STDERR at same time as STDOUT. You can choose between running threads to consume streams, or redirecting STDERR->STDOUT, or send both or merged streams to a file with Process.redirectOutput(File)
and Process.redirectError(File)
before calling processBuilder.start()
. Read this answer.
Upvotes: 2