Warm tip: This article is reproduced from serverfault.com, please click

Java Runtime exec throws no such file or permission denied

发布于 2012-06-14 11:17:51

My program is running on ubuntu 10.04 ,and here is the code :

Process process=Runtime.getRuntime().exec("ls",null,null);

it throw an exception of :

Cannot run program "ls": java.io.IOException: error=2, No such file or directory,  

and i tried to change "ls " to "chmod" ,"pwd" ,i found no one shell command work, all came to the same problem .(I also tried "/bin/sh -c ls")

and then i change the code to :

Process process=Runtime.getRuntime().exec("/bin/ls",null,null);

it throw an exception of :

Cannot run program "/bin/ls": java.io.IOException: error=13, Permission denied

I have changed privilege of all the related files and directories to 777 so i really don't know what's wrong with it.

Thank you for your replies .

Questioner
libing
Viewed
0
Gray 2012-06-14 20:59:40
Process process=Runtime.getRuntime().exec("ls",null,null);

This is expected give a No such file or directory exception since ls is most likely not in the current working directory of your program. When you type ls from the Linux shell prompt, it uses the PATH environment variable to turn ls into /bin/ls. Runtime does not do this for you.

You need to specify the full path "/bin/ls". As @Ernest mentioned, you should be using the Runtime.exec("/bin/ls") method and not passing in the null arguments.

Process process=Runtime.getRuntime().exec("/bin/ls");

Your comments seem to indicate that even when you use this call, you are getting a Permission denied exception. This works for me from a standard Java executable. I assume that you can do a /bin/ls from the Linux command line successfully? /bin/ls (and the associated directories) should be 755 and not 777 which would be a security nightmare. But 777 should work.

Maybe you are running some sort of protected JDK? Applets, for example, do not have permissions to execute Unix commands for security reasons. Maybe you have a restrictive Java policy file and you need to add execute permissions?