Reputation: 23844
So I have this simple code:
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("ls");
which works fine. (pr input stream will give me the file names..)
However I want to make something like this work:
Process pr = rt.exec("~/ls");
I want to get the file names in the directory of the Home folder of the current logged in user.
What I get is:
Exception in thread "main" java.io.IOException: Cannot run program "~/ls": error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1047)
Upvotes: 2
Views: 44
Reputation: 533870
When you run a program, is is not the same as running a shell to parse your command line unless you actually call the shell
exec("/bin/sh", "-c", "ls ~");
or
exec("ls", System.getProperty("user.home"));
Note: when you specify the directory at the start, you want to run the command in that directory, not pass the directory to a command as an argument.
e.g.
/bin/ls
means run the ls
which is in the /bin
directory (with no arguments)
ls /bin
mean pass /bin
to the command ls
Upvotes: 2
Reputation: 7980
~
is an expansion handled by the shell, Java does not know about it.
To get the home directory use the java.home
property (with System.getProperty
)
Note if you want to run a program in a specific working directory, use ProcessBuilder
and call the directory
method.
Upvotes: 4