FSCoder95
FSCoder95

Reputation: 17

find command works not on java, but in system shell

In a Java programm I want to find the path a hidden file .file.xyz in the directory /my/dir. This contains a sub-folder which should not be searched, the excludedFolder.
So I search for this file with find. I exclude the desired folder with -prune.

String findCommand = "find /my/dir -path /my/dir/excludedFolder -prune -o -name .file.xyz -print";
try{
   Process process = Runtime.getRuntime().exec(findCommand);
   BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
   //nothing is shown here, but hsould
   bufferedReader.lines().forEach(System.out::println);
}catch(Exception e){
    System.err.println(e.getMessage());
}

If I paste the command in the terminal and execute it there. It works fine.
My OS is Ubuntu 16.04.
Could you please explain me why?

Upvotes: 0

Views: 450

Answers (2)

Andrew Henle
Andrew Henle

Reputation: 1

You're using the wrong exec() function of the Runtime class.

Given

String findCommand = "find /my/dir -path /my/dir/excludedFolder -prune -o -name .file.xyz -print";

the Java code

Runtime.getRuntime().exec(findCommand);

will try to run the file literally named "find /my/dir -path /my/dir/excludedFolder -prune -o -name .file.xyz -print" as the command.

You want to pass arguments to find, not run some long command that has a filename that looks like a command. To do that, you need to pass a String array to exec():

String findCommand[] = { "find", "/my/dir", "-path",
    "/my/dir/excludedFolder", "-prune", "-o", "-name", ".file.xyz", "-print" };
...
Runtime.getRuntime().exec(findCommand);

Upvotes: 0

Daniele
Daniele

Reputation: 2837

You need to invoke "sh" and pass to that program your piped command. Try:

ProcessBuilder b = new ProcessBuilder( "/bin/sh", "-c",
               "find /my/dir -path /my/dir/excludedFolder -prune -o -name .file.xyz -print" );

Upvotes: 1

Related Questions