0
    File information = new File(args[0],"temp.txt");
    information.createNewFile(); //shortcut for Stackoverflow
    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.redirectOutput(information); //does not work on standard output eiher
    processBuilder.command("find " + args[0] + " -atime +" + args[1]);
    processBuilder.start();

Throws:

java.io.IOException: Cannot run program "find /users/niclas -atime +365": error=2, No such file or directory
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
    at com.company.Main.find(Main.java:35)
    at com.company.Main.main(Main.java:14)
Caused by: java.io.IOException: error=2, No such file or directory
    at java.base/java.lang.ProcessImpl.forkAndExec(Native Method)
    at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:319)
    at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:250)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
    ... 3 more

On the command line the same string works just fine: find /users/niclas -atime +365 What could the reasons for that be?

Niclas
  • 127
  • 11

1 Answers1

1

When you pass a command to ProcessBuilder in the command(String...) method overload, you are supposed to pass a separate string for each of the command's parameters.

Otherwise it thinks that the name of the command is the first string - including the spaces etc. - it does no parsing. ProcessBuilder is not a shell and is incapable of doing complex parsing.

Use

processBuilder.command("find", args[0],"-atime",args[1]);

You do not need to use spaces, and if you have an argument that includes spaces, the spaces will be passed as part of the argument without change.

Note that you may need to use the full path, e.g. /usr/bin/find rather than just find.

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
  • Hey, thank you! iI works. Unfortunately, now my file keeps empty (the file I used to redirect). (While find path -atime time >> file works) – Niclas Jan 01 '20 at 10:06