Asi
Asi

Reputation: 65

Runtime.getRuntime().exec(command) always return 1

i am trying to run the following code on my mac

 String command = "find /XXX/XXX/Documents/test1* -mtime +10 -type f -delete";

Process p = null;
p = Runtime.getRuntime().exec(command);
p.getErrorStream();
int exitVal = p.waitFor();

and exitVal is always 1 and it won't delete the files Any Idea??

Upvotes: 4

Views: 3389

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

From my experimentation, find will return 1 when it fails to find any results (find: /XXX/XXX/Documents/test1*: No such file or directory)

First, you should really be using ProcessBuilder, this solves issues with parameters which contain spaces, allows you to redirect the input/error streams as well as specify the start location of the command (should you need it).

So, playing around with it, something like this, seemed to work for me (MacOSX)...

ProcessBuilder pb = new ProcessBuilder(
        new String[]{
            "find", 
            "/XXX/XXX/Documents/test1",
            "-mtime", "+10",
            "-type", "f",
            "-delete"
        }
);
pb.redirectErrorStream(true);
try {
    Process p = pb.start();
    InputStream is = p.getInputStream();
    int in = -1;
    while ((in = is.read()) != -1) {
        System.out.print((char)in);
    }
    int exitWith = p.exitValue();
    System.out.println("\nExited with " + exitWith);
} catch (IOException exp) {
    exp.printStackTrace();
}

Upvotes: 4

Related Questions