Runtime.getRuntime().exec(command) always

2019-07-04 11:50发布

问题:

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??

回答1:

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();
}


标签: java shell